Display ALL categories that a product belongs to in Magento

我与影子孤独终老i 提交于 2019-12-04 14:00:05

问题


I am conceptualizing a new Magento site which will have products that are included in several categories. What I am wondering is if I can display all categories a product is in on the product detail page. I know that it is possible to get the category, but is it possible to display a list of all categories which a product belongs to?

For example, a shirt may be included in the Shirts category, as well as in Designers and Summer. Ideally, I would like to be able to display the following:

More from:

   Men > Shirts

   Men > Designers > Barnabé Hardy

   Men > Summer


回答1:


This will get you the data you are looking for such as the category's name, URL, etc:

$currentCatIds = $_product->getCategoryIds();
$categoryCollection = Mage::getResourceModel('catalog/category_collection')
                     ->addAttributeToSelect('name')
                     ->addAttributeToSelect('url')
                     ->addAttributeToFilter('entity_id', $currentCatIds)
                     ->addIsActiveFilter();

then just iterate over the collection e.g.

foreach($categoryCollection as $cat){
  echo $cat->getName().' '.$cat->getUrl();
}



回答2:


Simple.

$_categories = $_product->getCategoryCollection()
foreach ($_categories as $_category)
    //do something with $_category



回答3:


You can use the following code to display all categories related to the selected product in the product detail page.

<?php $categories = $_product->getCategoryIds(); ?>
           <?php foreach($categories as $k => $_category_id): ?>
           <?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?> 
< <a href="<?php echo $_category->getUrl() ?>"><?php echo $_category->getName() ?></a>
           <?php endforeach; ?>


来源:https://stackoverflow.com/questions/4252547/display-all-categories-that-a-product-belongs-to-in-magento

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!