Skip to content

Instantly share code, notes, and snippets.

@kekkorider
Created November 18, 2016 08:56
Show Gist options
  • Save kekkorider/0e3b7d2de54e74704101a39506439f37 to your computer and use it in GitHub Desktop.
Save kekkorider/0e3b7d2de54e74704101a39506439f37 to your computer and use it in GitHub Desktop.
Magento hreflang module
<?php
class Inchoo_Alternate_Model_Observer
{
public function alternateLinks()
{
$headBlock = Mage::app()->getLayout()->getBlock('head');
$stores = Mage::app()->getStores();
$product = Mage::registry('current_product');
$category = Mage::registry('current_category');
$locale = Mage::app()->getLocale()->getLocaleCode();
$locale = substr($locale, 0, strpos($locale, '_'));
if ($headBlock) {
foreach ($stores as $store) {
if ($product) { // Product pages
$category ? $categoryId = $category->getId() : $categoryId = null;
$url = $store->getBaseUrl() . Mage::helper('inchoo_alternate')->rewrittenProductUrl($product->getId(), $categoryId, $store->getId());
} else if ($category) { // Category pages
$categoryId = $category->getId();
$oCat = Mage::getModel('catalog/category')->setStoreId($store->getId())->load($categoryId);
if( $oCat->getIsActive() ) {
$aCaturlkey = parse_url($oCat->getUrl());
$url = rtrim($store->getBaseUrl(), "/") . $aCaturlkey["path"];
}
} else { // Static pages
$url = $store->getCurrentUrl();
}
if ( strpos($url, '?') !== false ) {
$url = substr($url, 0, strrpos($url, "?"));
}
$storeCode = substr(Mage::getStoreConfig('general/locale/code', $store->getId()), 0, 2);
if ($locale != $storeCode) { // we exclude the current language
$headBlock->addLinkRel('alternate"' . ' hreflang="' . $storeCode, $url);
}
}
}
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment