【问题标题】:how to get category name of current product (on product detail page) in magento如何在magento中获取当前产品的类别名称(在产品详细信息页面上)
【发布时间】:2013-08-05 08:32:13
【问题描述】:

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

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

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

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

}

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

【问题讨论】:

    标签: php magento magento-1.5


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:
        <?php 
          $_category_detail=Mage::registry('current_category');
          echo  $_category_detail->getName(); //gives current  category name
          echo $_category_detail->getId(); //gives current category id
      ?>
      

      【讨论】:

      • 虽然这可以回答问题,但最好提供一些关于此代码如何提供帮助的解释。
      • 我不想变得笨拙,但是,这实际上是问题,而不是答案。用户提到上面的代码不适用于他/她的情况。我同意@vard,我们以前曾经从 SO 复制粘贴,但在不阅读问题的情况下复制粘贴到 SO 对我来说是新的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多