PHP Magento Tips

How to Get Magento Meta keywords Dynamically on Product Page?

Rate this posting:
{[['']]}

In order to generate Meta Keywords Dynamically for Product Page, We have to create Event in Magento.

Step 1:

In app/etc/modules/Mycompany_Getkeywords.xml add Below Code:


<?xml version="1.0"?>
<config>
  <modules>
    <Mycompany_Getkeywords>
      <active>true</active>
      <codePool>local</codePool>
      <depends>
              <Mage_Catalog />
      </depends>
      <version>0.1.0</version>
    </Mycompany_Getkeywords>
  </modules>
</config>

Step 2:


In app/code/local/Mycompany/Getkeywords/etc/config.xml add Below Code:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Mycompany_Getkeywords>
            <version>0.1.0</version>
        </Mycompany_Getkeywords>
    </modules>
    <global>
        <models>
            <mycompany_getkeywords>
                <class>Mycompany_Getkeywords_Model</class>
            </mycompany_getkeywords>
        </models>
    </global>
    <frontend>
        <events>
            <catalog_controller_product_view><!-- event observer -->
                <observers>
                    <Mycompany_Getkeywords>
                        <class>mycompany_getkeywords/observer</class>
                        <method>productView</method>
                    </Mycompany_Getkeywords>
                </observers>
            </catalog_controller_product_view>
        </events>
    </frontend>
</config> 

Step 3:

In app/code/local/Mycompany/Getkeywords/Model/Observer.php add Below Code:

<?php
class Mycompany_Getkeywords_Model_Observer {
public function productView(Varien_Event_Observer $observer)
    {
        $product = Mage::registry('current_product');
        
        if ($product && $product->getId()) {
            // Add Product keywords
            $keywords = $product->getMetaKeyword();
            // Add category name
            $categoryIds = $product->getCategoryIds();
            foreach ($categoryIds as $category_id) {
                $_cat = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($category_id);
                $catinfo = $catinfo.", ".$_cat->getName();
                $catnames = ltrim($catinfo,", ");
            }
            // Add product name
            $productname = $product->getName();

            // Generate dynamic meta keyword tag
            if (!empty($keywords)) {
                $dynamickeywords = $keywords.", ".$catnames.", ".$productname;
            } else {
                $dynamickeywords = $catnames.", ".$productname;
            }
            $product->setMetaKeyword($dynamickeywords);
        }
    }
} 

Additionally, you can set Meta Title with setMetaTitle and Meta Description with setMetaDescription.
Tag : Magento
0 Comments On "How to Get Magento Meta keywords Dynamically on Product Page?"

Back To Top