I'm using a code snippet I found here to list all the categories that a product is listed in on the product page.

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

However, I'm realizing that the list can get a bit unruly and not really necessary. How can I adapt this code to only show the child categories the product belongs to. I might even need to take it a step further and only show the LAST child categories the product belongs to. Any help?

2 Answers 2


You can use following code to avoid parent categories.

                    ->addAttributeToFilter('entity_id', $catIds)
                    ->addAttributeToFilter('level', array('gt'=>0));

    foreach($Category as $child):
            <a class="" href="<?php echo Mage::helper('core/url')->getHomeUrl().$child->getRequestPath().DS ?>">
                <li class="level3">                         
                    <span><?php echo $child->getName() ?></span>

you can use level attribute filter to get child categories. Now in my code I am avoiding only the parent level categories only.


I like the answer of programmer_rkt, but I would filter for children_count, so you get only the leaves of the category tree:

$categories = $product->getCategoryCollection()->addAttributeToFilter('children_count', 0);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.