Magento – How to Add Hreflang Tags to Pages

headerhreflangmagento-1.8multistorePHP

Hi using info from this site and around the web I have started to add hreflang tags to my magento store. They work and display as they should on the default (American)site, however on the alternate (Canadian)site it does not work, here is the code & how it displays.

<link rel="alternate" href="http://www.example.com<?php 
$urlString = Mage::helper('core/url')->getCurrentUrl();
$url = Mage::getSingleton('core/url')->parseUrl($urlString);
$path = $url->getPath();echo $path 
?>" hreflang="en-us" />
<link rel="alternate" href="http://www.example.com/ca<?php $urlString =
Mage::helper('core/url')->getCurrentUrl();                                                             
$url = Mage::getSingleton('core/url')->parseUrl($urlString);
$path = $url->getPath();echo $path ?>" hreflang="en-ca" />

which on the main site properly displays as (on a product page for example)

<link rel="alternate" href="http://www.example.com/sample-product.html" 
hreflang="en-us" />
<link rel="alternate" href="http://www.example.com/ca/sample-product.html" hreflang="en-ca" />

so far so good, however when you are on the Canadian ca site, it now displays as

<link rel="alternate" href="http://www.example.com/ca/sample-product.html" hreflang="en-us" />
<link rel="alternate" href="http://www.example.com/ca/ca/sample-product.html" hreflang="en-ca" />

as you can see there is an extra (/ca/) on each url. I'm not quite sure how to tackle this problem, I guess what I need is the code to output everything after the base url as opposed to the domain of each site. Any help that you could provide will be greatly appreciated! Thank you.

Best Answer

In my case, I wanted to do different hreflangs for each website. So to do just for the current one:

$website = Mage::app()->getWebsite()->getStores();
foreach ( $website as $store) {
    $lang = $store->getConfig('general/locale/code');
    echo '<link rel="alternate" href="' . $store->getCurrentUrl() . '" hreflang="' . $lang . '"/>' . "\n";
}

There is one more thing to point out, $lang = $store->getConfig('general/locale/code'); generates language tags like so: "en_GB". As Google states, that is incorrect, it should have been: "en-gb" (dash not underscore, small caps) or "en", depended on what you wan to achieve - link.

I use the code directly in templates, as it each of my website has its own template - it should go to app/design/frontend/yourPackage/yourTemplate/template/page/html/head.phtml

An example of replacing language tags as asked in comments - in most cases we only use "non targeted" language tags (two leter ISO codes):

$lang = $store->getConfig('general/locale/code');
    if (strtolower($lang) == 'en_us'){
        $lang = 'en'; //OR en-gb or any tag you need
    }
    echo '<link rel="alternate" href="' . $store->getCurrentUrl() . '" hreflang="' . $lang . '"/>' . "\n";
Related Topic