Display ALL categories that a product belongs to in Magento

11,681

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

Solution 2

Simple.

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

Solution 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; ?>
Share:
11,681
Jason
Author by

Jason

Educator, technology consultant, GTD enthusiast, and web programmer in Vancouver, Canada.

Updated on June 04, 2022

Comments

  • Jason
    Jason almost 2 years

    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

  • Jason
    Jason over 13 years
    Thanks, JD. I'll give that a try!
  • robgt
    robgt about 12 years
    Is there a way to display the full category path (with links at each stage) rather than only displaying the final category that a product belongs to?
  • robgt
    robgt about 12 years
    That's pretty much it, yes. Having done a lot of searching for an answer to this, I found that Magento's definition of a breadcrumb differs from most of everyone elses - but yes, I would call it a breadcrumb.
  • robgt
    robgt about 12 years
    Asked and answered here: stackoverflow.com/questions/9531702/…