how to get category name of current product (on product detail page) in magento
Asked Answered
D

2

7

I used following codes but didn't work for this case:

$_category_detail=Mage::registry('current_category');
echo $_category_detail->getName();

got Fatal error: Call to a member function getName() on a non-object in /app/design/frontend/base/default/template/catalog/product/view.phtml

we make some filters and use below mention code in head.phtml:

$is_product = Mage::registry('product');

if($is_product){ 

  if(is_object(Mage::registry('current_category'))){ 
    $category_name = Mage::registry('current_category')->getName(); 
  }
  else{ $category_name = ""; }

}

But this only works if you go from a category to a product. If you visit the product page directly nothing is being displayed

Dapplegray answered 5/8, 2013 at 8:32 Comment(0)
D
23

It's because products can be attached to multiple categories. In your situation, when you visit a product page referred from a category page, your session has category information. But if you visit directly product page, Magento can not know which category you came from, so it can not show you a specific category, because your product can have multiple categories.

But in your situation, if your products are attached only one category, you can use this code, it shows first category name of product;

        $categoryIds = $_product->getCategoryIds();

        if(count($categoryIds) ){
            $firstCategoryId = $categoryIds[0];
            $_category = Mage::getModel('catalog/category')->load($firstCategoryId);

            echo $_category->getName();
        }
Danelaw answered 5/8, 2013 at 9:45 Comment(0)
M
3
  <?php 
    $_category_detail=Mage::registry('current_category');
    echo  $_category_detail->getName(); //gives current  category name
    echo $_category_detail->getId(); //gives current category id
?>
Moten answered 18/1, 2016 at 7:20 Comment(2)
While this can answer the question, it's better to provide some explanations about how this code help.Curate
I dont want to be mangy but, this was actually the question, not the answer. User mentioned that the code above didn't worked for his/her situation. I agree with @vard, we used to copy pasters from SO before but copy pasting to SO without reading the question is new for me.Danelaw

© 2022 - 2024 — McMap. All rights reserved.