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

$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>';

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?


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


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.

| improve this answer | |

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.