How to get the category name of the current product (on the product details page) in magento

I used the following codes, but did not work for this case:

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

received Fatal error: Calling member function getName () for non-object in /app/design/frontend/base/default/template/catalog/product/view.phtml

we make some filters and use the mention code below 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 it only works if you are moving from category to product. If you visit the product page, nothing is displayed.

+6
source share
2 answers

This is because products can be attached to several categories. In your situation, when you visit the product page indicated on the category page, your session contains category information. But if you go directly to the product page, Magento cannot know which category you came from, so it cannot show you a specific category because your product can have several categories.

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

  $categoryIds = $_product->getCategoryIds(); if(count($categoryIds) ){ $firstCategoryId = $categoryIds[0]; $_category = Mage::getModel('catalog/category')->load($firstCategoryId); echo $_category->getName(); } 
+20
source
  <?php $_category_detail=Mage::registry('current_category'); echo $_category_detail->getName(); //gives current category name echo $_category_detail->getId(); //gives current category id ?> 
+3
source

Source: https://habr.com/ru/post/951022/


All Articles