Magento SEO PHP Product, Category Descriptions and defaults
Posted on November 1, 2013 by Daniel Chadwick
Struggling to generate meta keywords or descriptions automatically on your Magento category and product pages? This blog should help you through the code needed.
Magento is great for many things and from an SEO development point of view it is pretty good but not perfect. Our SEO maestro wanted me to implement some code that if there was a product description it would use that to populate the meta description. After doing some searching, I came across this blog post. This gave me a good starting point but I also needed to do this for category pages as well and our set up required that I looked into a couple of other things. The main issue was that we had populated the default meta description and keywords already so the code needed to check if the keywords for the product where not empty and not equal to the default before deciding what to do.
The code I ended up with is placed in the page/html/head.phml of the theme we are using:
<?php $desc = strip_tags(trim($this->getDescription())); $kw = trim($this->getKeywords()); $title = strip_tags(trim($this->getTitel())); if (Mage::registry('current_product')) { $desc = $this->getTitle(). ' '. strip_tags(str_replace("<br />",", ",substr(Mage::registry('current_product')->getDescription(), 0, strpos(Mage::registry('current_product')->getDescription(), '.')+1))); $desc = substr($desc, 0, 150); if($title = Mage::getStoreConfig('design/head/default_title') || $title == Mage::registry('current_product')->getDescription()) { if(strtolower(substr($desc, 0, strlen($title))) !== strtolower($title)) { $title = Mage::registry('current_product')->getName().' '.strip_tags($desc); } } if(empty($kw) || $kw == Mage::getStoreConfig('design/head/default_keywords')) { $kw = $title.','.$kw; } } if (Mage::registry('current_category')) { if(empty($desc) || $desc == Mage::getStoreConfig('design/head/default_description')) { $desc = $this->getTitle(). ' '. strip_tags(str_replace("<br />",", ",substr(Mage::registry('current_category')->getDescription(), 0, strpos(Mage::registry('current_category')->getDescription(), '.')+1))); $desc = substr($desc, 0, 150); } if(empty($kw) || $kw == Mage::getStoreConfig('design/head/default_keywords')) { $kw = $title.','.$kw; } } // ... do what is necessary <title..., <meta name="description... etc ?>
As you can see from the code ; there are quite a few checks and replacements going on to ensure html is not passed through to the head items and also to ensure there isn’t too much duplication of the product name in the description.