Viewing 2 replies - 1 through 2 (of 2 total)
  • I just wrote a function and popped it in the functions.php on each site (if you’re using a separate child theme for each):

    add_action('wp_head', 'arwd_hreflang_head');
    function arwd_hreflang_head(){
    global $post;
    if(is_page()) {
    $url = $_SERVER['REQUEST_URI'];
    ?>
    <link rel="alternate" href="<?= 'https://domain.co.uk'.$url ?>" hreflang="en-gb" />
    <link rel="alternate" href="<?= 'https://domain.com'.$url ?>" hreflang="en" />
    <?php }
    }

    This adds it to the header on every page on the site. My two sites are exact copies of one another so there is always a matching page on the sister site.

    Thread Starter SRD75

    (@srd75)

    Thanks @arapps92

    I can see your solution is simpler than ours. We use the same theme for all 3 sites, so we came up with:

    function mm_add_hreflang_attribute() {
        if (!( is_singular( 'locations' ) ) ) {
            $sites = array(
                array('', 'x-default'),
                array('', 'en'),
                array('en-gb/', 'en-gb'),
                array('en-au/', 'en-au'),
            );
            
            if ( is_post_type_archive('locations') ) {
                foreach ( $sites as $site ) {
                    $site_url = network_site_url();
                    $page_path = 'locations/';
                    $geo_url = $site[0];
                    $hreflang = $site[1];
                    $url = $site_url . $geo_url . $page_path;
                    echo '<link rel="alternate" href="' . $url . '" hreflang="' . $hreflang . '" />'. PHP_EOL;
                }
            } elseif ( is_archive() ) {
                foreach ( $sites as $site ) {
                    $site_url = network_site_url();
                    $request   = $GLOBALS['wp']->request;
                    $page_path = trim( preg_replace( '#^blog/topic/#', '', $request ), '/' );
                    $geo_url = $site[0];
                    $hreflang = $site[1];
                    $url = $site_url . $geo_url . 'blog/topic/' . $page_path . '/';
                    echo '<link rel="alternate" href="' . $url . '" hreflang="' . $hreflang . '" />'. PHP_EOL;
                }
            } else {
                foreach ( $sites as $site ) {
                    $site_url = network_site_url();
                    $page_path = substr(get_permalink(), strlen(home_url('/')));
                    $geo_url = $site[0];
                    $hreflang = $site[1];
                    $url = $site_url . $geo_url . $page_path;
                    echo '<link rel="alternate" href="' . $url . '" hreflang="' . $hreflang . '" />'. PHP_EOL;
                }
            }
        }
    }
    add_action( 'wp_head', 'mm_add_hreflang_attribute', 1 );
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to set hreflang links’ is closed to new replies.