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. Ideal开发者_运维问答ly, I would like to be able to display the following:
More from:
Men > Shirts
Men > Designers > Barnabé Hardy
Men > Summer
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();
}
Simple.
$_categories = $_product->getCategoryCollection()
foreach ($_categories as $_category)
//do something with $_category
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; ?>
精彩评论