Custom Magento Canonical Tags

I’ve just done some modifications to a magento install which I administer to allow custom canonical tags to be specified in the “Custom Layout Update” field of product items and categories. Magento is notoriously bad for url canonicalisation out of the box, as it generates at least 4 urls for each product, all with almost identical content. So I copied head.php from /app/code/core/Mage/Page/Block/Html into /app/code/local/Mage/Page/Block/Html and added the following customisations.

Index: Head.php
===================================================================
--- Head.php	(revision 152)
+++ Head.php	(working copy)
@@ -93,7 +93,8 @@
         $script = '';
         $stylesheet = '
';
         $alternate = '
';
-
+		$canonical = '
';
+
         foreach ($this->_data['items'] as $item) {
             if (!is_null($item['cond']) && !$this->getData($item['cond'])) {
                 continue;
@@ -122,6 +123,9 @@
                 case 'rss':
                     $lines[$if]['other'][] = sprintf($alternate, 'application/rss+xml'/*'text/xml' for IE?*/, $item['name'], $item['params']);
                     break;
+                case 'canonical':
+                    $lines[$if]['other'][] = sprintf($canonical, $item['name'], $item['params']);
+                    break;
             }
         }

Ignore the revision numbers (I have my own SVN repo codebase) – this was based on Magento 1.3.2.1. The snip below shows how to make use of this in the custom layout field

 

		canonical

http://www.yourdomain.com/your-chosen-canonical-url.html

Switch to our mobile site