How to Add Rel Canonical Tag to Magento

Important Note: This script has been updated. Now, it first checks the page type, then it adds the canonical links if the page is a CMS page. Please note that Magento has a built in support for canonical links for categories and products. So, you really need to add the canonical tags to your CMS pages only.

I recently needed to add rel canonical tags to Magento Community Edition on every cms page. The default canonical generation feature that comes embedded with Magento works with Categories and Products only, not with CMS pages.

I wanted my canonical links to be with (www), so, this example assumes you also want to achieve the same result.

There are some extensions that do this out of the box. But, I did not want to add an extension to achieve something as simple as this.

Here is a simple way to do it. You will need to edit the head.phtml of your active theme. This should be under /app/design/frontend/theme_name/default/template/page/html/head.phtml.

Add the following in your theme’s head.phtml before the closing of the head section.

<?php

/*
Canonical Link snippet
Code by: Mohamed Elgharabawy [ItsCoding.com]
This will show the canonical links on CMS pages. You do not need this on catalogue and product pages as Magento has that function in place already
*/

// get the page type: CMS, Catalog, .. etc
$pageType = $this->getRequest()->getModuleName();
// if page type is cms, put the canonical link
if ($pageType == "cms")
 {
 $currentUrl = Mage::helper('core/url')->getCurrentUrl();
 $url = Mage::getSingleton('core/url')->parseUrl($currentUrl);
 $path = $url->getPath();
?>
<!-- Canonical link with (www) -->
<link rel="canonical" href="<?php echo "http://www.yourWebsite.com".$path; ?>" />
<?php
 }
?>

The $path variable returns the URL content after the base url. So, just take the above snippet, change (yourWebsite.com) to your store URL and you will be good to go.

This was tested with Magento Community Edition 1.9.2.1.

Hope this helps!

Summary
How to Add Rel Canonical Tag to Magento
Article Name
How to Add Rel Canonical Tag to Magento
Description
How to add rel canonical tags to Magento Community Edition on every cms page without using any extensions.
Author
Publisher Name
ItsCoding.com
Publisher Logo
Share This:

Published by

Mohamed Elgharabawy

Linux devotee. Red Hat to be exact. Loves WordPress, PHP, jQuery, HTML, and CSS.

3 thoughts on “How to Add Rel Canonical Tag to Magento”

Leave a Reply to Mohamed Elgharabawy Cancel reply

Your email address will not be published. Required fields are marked *