Magento 1.9 – How to Get Current Category Name in an Observer

categorymagento-1.9

I want to get the name of current category name of a product after add to cart for this I'm using this $category = Mage::registry('current_category') but it shows null on observer.

so which observer I should call to get this value after add to cart the product.

Please help me thank you.

Best Answer

You should use following way to get product's categories in observer.

Declare event observers in config.xml

<events>
    <checkout_cart_product_add_after>
        <observers>
            <custommodule>
                <class>custommodule/observer</class>
                <method>cartProductAddAfter</method>
            </custommodule>
        </observers>
    </checkout_cart_product_add_after>
    <checkout_cart_product_update_after>
        <observers>
            <custommodule>
                <class>custommodule/observer</class>
                <method>cartProductUpdateAfter</method>
            </custommodule>
        </observers>
    </checkout_cart_product_update_after>
</events>

Develop the Observers handlers

class Vendor_Custommodule_Model_Observer 
{
    /* If you'd like to do the same while updating the shopping cart*/
    public function cartProductUpdateAfter($observer)
    {
        $this->cartProductAddAfter($observer);
    }

    public function cartProductAddAfter($observer)
    {
        $product_id = $observer->getEvent()->getProduct()->getId();

        //Get the category ids
        $product = Mage::getModel('catalog/product')->load($product_id);
        $cats = $product->getCategoryIds();

        //One product can associate with more then one categories. 
        foreach ($cats as $category_id) {
            $_cat = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($category_id);
            echo $_cat->getName();             
        }
    }
}

Another way

public function cartProductAddAfter($observer)
    {
        $_product = $observer->getEvent()->getProduct();
        $catIds = $_product->getCategoryIds();
        $catCollection = Mage::getResourceModel('catalog/category_collection')
                         ->addAttributeToSelect('*')
                         ->addAttributeToFilter('entity_id', $catIds)
                         ->addIsActiveFilter();

        foreach($catCollection as $cat){
            print_r($cat->getData());
            //echo $cat->getName();
            //echo $cat->getUrl();
        }
    }
Related Topic