Reputation: 263
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
Upvotes: 3
Views: 11851
Reputation: 504
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; ?>
Upvotes: 1
Reputation: 37700
Simple.
$_categories = $_product->getCategoryCollection()
foreach ($_categories as $_category)
//do something with $_category
Upvotes: 1
Reputation: 18692
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();
}
Upvotes: 8