且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在magento中获取当前产品的类别名称(在产品详细信息页面上)

更新时间:2022-10-27 17:41:53

这是因为产品可以附加到多个类别.根据您的情况,当您访问从类别页面引用的产品页面时,您的会话具有类别信息.但是,如果您直接访问产品页面,Magento将无法知道您来自哪个类别,因此无法显示特定类别,因为您的产品可以具有多个类别.

但是在您的情况下,如果您的产品仅附有一个类别,则可以使用此代码,它显示产品的第一类别名称;

        $categoryIds = $_product->getCategoryIds();

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

            echo $_category->getName();
        }

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

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();
        }