hreflang Tags for Regional Versions of Your Site
Links matching pages across your country sites (such as example.com, example.co.uk and example.com.au) with hreflang tags, assuming each page uses the same path on every domain.
Opens WPIDE on
Code
// Language-region code => site address (no trailing slash). x-default is used for everyone else.
$wpide_regional_sites = array(
'en-US' => 'https://example.com',
'en-GB' => 'https://example.co.uk',
'en-AU' => 'https://example.com.au',
'x-default' => 'https://example.com',
);
add_action( 'wp_head', function () use ( $wpide_regional_sites ) {
if ( is_404() || is_search() || is_preview() || ( is_singular() && post_password_required() ) ) {
return;
}
$path = (string) wp_parse_url( home_url( add_query_arg( array() ) ), PHP_URL_PATH );
$base = (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH );
$path = '/' . ltrim( substr( $path, strlen( rtrim( $base, '/' ) ) ), '/' );
foreach ( $wpide_regional_sites as $lang => $site ) {
printf( '<link rel="alternate" hreflang="%1$s" href="%2$s">' . "\n", esc_attr( $lang ), esc_url( untrailingslashit( $site ) . $path ) );
}
} );
Notes
Add this to every regional site with the same map. Pages whose path differs between sites need a multilingual plugin instead.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.