Magento 1.8 – Dynamic Change Meta Description

magento-1.8meta-tags

Is there a way to set dynamic meta-descriptions by changing the Magento code.
For instance:

"Buy PRODUCT_NAME online and save PERCENTANGE% today. Free shipping
and secure payments"

In the above case PRODUCT_NAME would be the actual prodcut name. But PERCENTAGE would require some coding as its changed over time. (In my case it would be something like 1-(price/suggested_price). As you understand the percentage would not be the same for all products so it needs to be updated dynamically and this is just for the products.

Best Answer

I see 3 ways to tackle this.
Option 1.
Have a cron that runs every night that builds this meta description for each product. This way you don't interfere with the Magento flow for frontend.

The code can look something like this (untested)

$storeViews = Mage::getModel('core/store')->getCollection();
foreach ($storeViews as $store) {
    if ($store->getId() == 0) {
        continue; //skip admin store
    }
    $collection = Mage::getModel('catalog/product')->setStoreId($store->getId())->getCollection()->addAttributeToSelect('*');
    foreach ($collection as $product) {
        $metaDescription = 'Buy '.$product->getName().' online and save '.CUSTOM LOGIC HERE FOR THE PERCENTAGE.'% today. Free shipping and secure payments';
        Mage::getSingleton('catalog/product_action')->updateAttributes(
             array($product->getId()),
             array('meta_description' => $metaDescription),
             $store->getId()
        )
    }
}

This makes sense if your meta descriptions are going to change a lot and if you don't have a lot of products.

Option 2.
Rewrite the product model Mage_Catalog_Model_Product and add a method called getMetaDescription() like this:

public function getMetaDescription() {
    $name = $this->getName();
    $percentage = ...custom logic for percentage
    return Mage::helper('catalog')->__('Buy %s online and save %s % today. Free shipping and secure payments', $name, $percentage);
}

This will generate the meta description on the fly. It makes sense if you don't have a very complicated discount formula. I would choose this one. I wrote it as the second one (in the middle) to see if you are paying attention. :)

Option 3.
Is very similar to the one above, but involves modifying the block that adds the meta description. You should use this in case you don't want to touch the product model.
You have to rewrite the Mage_Catalog_Block_Product_View and in the method _prepareLayout replace $description = $product->getMetaDescription(); with

$name = $product->getName();
$percentage = ...custom logic for percentage
$description = Mage::helper('catalog')->__('Buy %s online and save %s % today. Free shipping and secure payments', $name, $percentage);
Related Topic