Magento 1.8 – Mage::Registry(‘current_category’) Working in Catalog List but Not in Catalog Product View

catalogmagento-1.8

in order to retrieve categories path im using the following piece of code in phtml files:

<?php $currentCat = Mage::registry('current_category'); ?>
<?php $exp = explode("/", $currentCat->getPath());?>

I dont understand why,

class Mage_Catalog_Block_Product_List

and its associate catalog/product/list.phtml display the information eg: 1/3/54,

on the other hand,

class Mage_Catalog_Block_Product_List

and its associate catalog/product/view.phtml is not displaying any information. I receive

Fatal error: Call to a member function getPath() on a non-object in
\template\page\product.phtml on line 2

I dont know what Im missing, I supposed mage::registry('current_category') was a global variable. and it seems that is not set.

Best Answer

Here is the function where it is defined.

It gets the categoryId here:

$categoryId = (int) $this->getRequest()->getParam('id', false);

If that's not in the request path, it won't set 'current_category'.

A product can be in several categories, so when you route to the product directly, it doesn't know the category. There are several ways to find the parent categories of a product, but you will have to find the right method for you. It's easy if you don't put products in more categories but more complex if you do.

Alan Storm's answer here can get you started: https://stackoverflow.com/questions/15735324/get-a-products-parent-category-even-if-it-is-accessed-directly

   protected function _initCatagory()
        {
            Mage::dispatchEvent('catalog_controller_category_init_before', array('controller_action' => $this));
            $categoryId = (int) $this->getRequest()->getParam('id', false);
            if (!$categoryId) {
                return false;
            }

            $category = Mage::getModel('catalog/category')
                ->setStoreId(Mage::app()->getStore()->getId())
                ->load($categoryId);

            if (!Mage::helper('catalog/category')->canShow($category)) {
                return false;
            }
            Mage::getSingleton('catalog/session')->setLastVisitedCategoryId($category->getId());
            Mage::register('current_category', $category);
            try {
                Mage::dispatchEvent(
                    'catalog_controller_category_init_after',
                    array(
                        'category' => $category,
                        'controller_action' => $this
                    )
                );
            } catch (Mage_Core_Exception $e) {
                Mage::logException($e);
                return false;
            }

            return $category;
        }
Related Topic