I have been trying to add hreflang tags to a multi-language project following the answers to this question. In my setup there is one website, one store and there are three store views (English, German and Dutch).
The code that I'm currently using in
[my Magento install dir]/app/design/frontend/MYPACKAGE/MYTHEME/template/page/html/head.phtml
is the following
<?php foreach (Mage::app()->getWebsites() as $website) {
foreach ($website->getGroups() as $group) {
$stores = $group->getStores();
foreach ($stores as $store) {
$storeCode = $store->getCode();
echo '<link rel="alternate" hreflang="' . $storeCode . '" href="' . $store->getCurrentUrl(false) . '"/>' . "\n";
}
}
}
?>
This outputs the hreflang tags like this
<link rel="alternate" hreflang="en" href="domain.com/en/bags.html">
<link rel="alternate" hreflang="de" href="domain.com/de/bags.html">
<link rel="alternate" hreflang="nl" href="domain.com/nl/bags.html">
At first glance this looks perfect, however there is this one problem. The store is using different URL Keys per language (store view). To improve SEO, the URL Keys are translated to match the language of the store view. For store views other than the one that is selected, the current hreflang tags point to URLs that do not exist (resulting in 404 Page not Found errors).
So the hreflang tags that I am looking for should look like this
<link rel="alternate" hreflang="en" href="domain.com/en/bags.html">
<link rel="alternate" hreflang="de" href="domain.com/de/taschen.html">
<link rel="alternate" hreflang="nl" href="domain.com/nl/tassen.html">
How can I get the hreflang tags to match the proper URL Key for each store view?
UPDATE July 16, 2015
Even though I have not accepted Marius his answer (because I did not manage to get his second solution to work for me) I used his first approach and created 301 redirects for all pages in different languages.
This seemed to work out just fine but last week Google started sending out error messages to users for incorrect implementation on Hreflang through Google Search Console.
In the Search Console it says that Google has found URLs for my 'en' site and alternate URLs in 'nl' that do not have return tags. A screen shot of the console is below.
The Alternate 'en' URLs that Google is listing do appear in the <head>
section of my site, but I have set 301 redirects to the 'nl' URLs in the Magento Admin Panel.
For some reason Google handles this as incorrect implementation of hreflang tags.