Magento – How to get only child categories of a product. Magento 1.8.1

categoryce-1.8.1.0product

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

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

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?

Best Answer

You can use following code to avoid parent categories.

<?php
    $catIds=$_product->getCategoryIds();
    $Category=Mage::getSingleton('catalog/category')->getCollection()
                    ->addAttributeToFilter('entity_id', $catIds)
                    ->addAttributeToFilter('level', array('gt'=>0));

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

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

Related Topic