0

I'm using the following code to display the subcategory of specific categories in a hardcoded mega menu:

<?php
$children = Mage::getModel('catalog/category')->getCategories(3);
foreach ($children as $category):
    $category = Mage::getModel('catalog/category')->load($category->getId());
    echo '<li><a href="' . $category->getUrl() . '">' . $category->getName() . '</a></li>';
endforeach;?>

This works great, but some of these subcategories has subcategories of their own, and I would like to display those too. How do I modify the above to include another level?

2

Loading each category individually is a lot slower then loading all at once. It's better to load all, and then just pick the ones you need.

So lets assume you have a loaded base category and want to iterate over all children recursively

$baseCategory->load(3);

Fetch all children, regardless of depth:

$allChildren = $baseCategory->getCollection()
    ->addFieldToFilter('path', array('like' => $baseCategory->getPath() . '/%'));
// Put some addAttributeToSelect() here if needed

Then, loop over all children:

$children = $allChildren->getItemsByColumnValue('parent_id', $baseCategory->getId());
foreach ($children as $child) {
    // Do whatever you want to do here
    // Then go one level deeper:
    $secondLevelChildren = $allChildren->getItemsByColumnValue('parent_id', $child->getId());
    foreach ($secondLevelChildren as $child2) {
        // .. and so on
    }
}

If you want to simply recurse to the bottom, use a recursive function instead of nested loops.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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