3
votes

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

3

3 Answers

8
votes

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();
}
1
votes

Simple.

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

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; ?>