7

我使用了以下代码,但不适用于这种情况:

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

出现致命错误:在 /app/design/frontend/base/default/template/catalog/product/view.phtml 中的非对象上调用成员函数 getName()

我们制作了一些过滤器并在 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 = ""; }

}

但这仅在您从类别转到产品时才有效。如果您直接访问产品页面,则不会显示任何内容

4

2 回答 2

23

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

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

        $categoryIds = $_product->getCategoryIds();

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

            echo $_category->getName();
        }
于 2013-08-05T09:45:42.997 回答
3
  <?php 
    $_category_detail=Mage::registry('current_category');
    echo  $_category_detail->getName(); //gives current  category name
    echo $_category_detail->getId(); //gives current category id
?>
于 2016-01-18T07:20:43.680 回答