Magento – Call to a member function getName() on a non-object product view page

ifmagento-1.9product-view

I have the following code on my product view page, calling the product's containing category title :

   <div class="page-title category-title">
       <h1><?php echo $_category->getName(); ?></h1>
   </div>

The issue I have is that if a user visits the page directly (i.e. not through a category) then this results in a call to non-object error. Can anyone suggest an edit so that when the user visits the product page directly the category title will not display?

Best Answer

If you will access product from the category page you will get the category in the registry. and if you access the product directly by URL you will need to fetch category name from product object.

<?php
if (Mage::registry('current_category')) {
    echo Mage::registry('current_category')->getName();
}
else {
    $categoryIds = $_product->getCategoryIds();
    if (count($categoryIds)) {
        $firstCategoryId = $categoryIds[0];
        $_category = Mage::getModel('catalog/category')->load($firstCategoryId);

        echo $_category->getName();
    }
}
?>
Related Topic