Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.