Hreflang without "current" language

Hi there, I like to implement hreflang for SEO purposes.
Since I am not a php pro, I customized a language switch used in the footer.

<?php foreach($site->languages() as $language): ?>
    <link rel="alternate" hreflang="<?php echo html($language->code()) ?>" href="<?php echo $page->url($language->code()) ?>" />
    <?php endforeach ?>

This kind of works, but I want not to output the line in the header for the currently displayed page.

Thanks in advance!
Martin

Try this:

<?php foreach($site->languages() as $language): ?>
  <?php if($language == $site->language()) continue; ?>

<?php endforeach ?>

That works, thanks so much!

I like that continue bit a lot!
I would have wrote something which adds an unnecessary endif…

<?php foreach($site->languages() as $language): ?>
  <?php if($language != $site->language()): ?>
    Your code here...
  <?php endif ?>
<?php endforeach ?>

Hi,
Google suggest that you to include the hreflang tag also to the page itself:

If you have multiple language versions of a URL, each language page should identify different language versions, including itself. For example, if your site provides content in French, English, and Spanish, the Spanish version must include a rel=“alternate” hreflang=“x” link for itself in addition to links to the French and English versions. Similarly, the English and French versions must each include the same references to the French, English, and Spanish versions.

https://support.google.com/webmasters/answer/189077?hl=en

1 Like

Here is the full code. It also checks, if there actually is a version of that page in that language:

<?php foreach($site->languages() as $language): ?>
<?php if($language != $site->language() && $page->content($language->code())->exists()): ?>		
<link rel="alternate" hreflang="<?php echo html($language->code()) ?>" href="<?php echo $page->url($language->code()) ?>" />
<?php endif ?>
<?php endforeach ?>