Wordpress multiple hreflang to single url, HOW?

1k Views Asked by At

As stated in this post https://www.rebelytics.com/multiple-hreflang-tags-one-url/ multiple hreflangs can be assigned to single urls.

So I would like to use multiple hreflang tags for english speaking countries pointing to the same url, so I can benefit from SEO perspective without need of generating new urls for each of these countries.

I want to use this example:

<link rel="alternate" href="https://www.yourwebsite.com/" hreflang="x-default">
<link rel="alternate" href="https://www.yourwebsite.com/en/about/" hreflang="en">
<link rel="alternate" href="https://www.yourwebsite.com/en/about/" hreflang="en-gb">
<link rel="alternate" href="https://www.yourwebsite.com/en/about/" hreflang="en-ie">
<link rel="alternate" href="https://www.yourwebsite.com/en/about/" hreflang="en-ca">

But how can I make it work for all wordpress pages (urls)? Thanks!

1

There are 1 best solutions below

3
On BEST ANSWER

You can try this:

function add_multiple_hreflang_to_head() {
  $current_url = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // change to http if you don't use ssl
  if (strpos($current_url, '/en/') !== false) :
  ?>
    <link rel="alternate" href="<?php echo $current_url; ?>" hreflang="x-default">
    <link rel="alternate" href="<?php echo $current_url; ?>" hreflang="en">
    <link rel="alternate" href="<?php echo $current_url; ?>" hreflang="en-gb">
    <link rel="alternate" href="<?php echo $current_url; ?>" hreflang="en-ie">
    <link rel="alternate" href="<?php echo $current_url; ?>" hreflang="en-ca">
  <?php
  endif;
}
add_action('wp_head', 'add_multiple_hreflang_to_head');

If the URL contains '/en/' it loads the links into <head>. You can add this code to the (child) theme functions.php or a PHP snippet plugin.