Division By Zero

Dynamically generate category meta descriptions in Magento

First we found the class responsible for setting up a category for display. This is View.php in /app/code/core/Mage/Catalog/Block/Category.

Inside the function _prepareLayout is a little bit of code that looks like this:


if ($description = $this->getCurrentCategory()->getMetaDescription()) {
    $headBlock->setDescription($description);
}

If the current category has its own meta description entered in the admin it will be assigned to the variable $description, which will then be set in the headBlock as the meta desc. But in the case of our categories this code never runs, so Magento falls back on the default.

So I added an else block like so:


if ($description = $this->getCurrentCategory()->getMetaDescription()) {
    $headBlock->setDescription($description);
}
else
{
    if($catName = $this->getCurrentCategory()->getName())
    {
        $description = 'Free delivery on ' .
                            $catName .
                            ' from Epik Performance. For the best ' .
                            $catName .
                            ' look no further than Epik Performance!';
        $headBlock->setDescription($description);
    }
    else
    {
        //no cat name found, must leave as default
    }
}

All this does is grab the current category’s name and place it into a custom meta description template string. Not the most elegant solution I know (core file modified, hard coded string) and the code can be tidied a bit, but when I get time I’ll do something to turn this into a nice standalone class / module. We just needed a quick and dirty solution for now.

Anyway I hope this is of use to someone, and if you’re interested in high quality car exahusts, turbos and other stuff why not have a look at my friend’s site, www.epikperformance.co.uk.

Spread the word

If you like what you've read, help spread the word on Twitter, Digg, or any of your favourite social sites. Knowledge is power.

About the author

Jonathan Phillips is the founder and main author here on Division by Zero. A PHP developer by trade, Jonathan spends his days building and marketing websites and the rest of the time coming up with ideas for websites and businesses he hasn't got time to implement.

2 Comments

  1. Chris Head 1
    August 2, 2010
    at 2:26 pm
    Reply

    Awesome post, worked exactly as described :-)

    • August 2, 2010
      at 6:01 pm
      Reply

      Thanks Chris ;) At some point I’ll have to write an extension or something that does this so there’s no core-hacking going on.

Leave a comment

* denotes a required field

Don't worry, your email address etc. is safe, we won't share it with anyone.

Copyright © 2009 - 2010 Division By Zero - Credits