Search code examples
phpperformancemagentomagento-1.8

Magento get child categories / category collection handling. Programming efficiency


Ok, the code I have written below works great, however I have some pages that may hit a few hundred categories and I do not want to ping the database every time through the foreach loop. Basically looking for a better way to handle the collection. Secondly, is there a way I can verify that this category is active.

<ul>
    <?php $_helper       = Mage::helper('catalog/category') ?>
    <?php $_categories   = $_helper->getStoreCategories() ?>

    <?php foreach($_categories as $_category): ?>
        <?php $_category      = Mage::getModel('catalog/category')->load($_category->getId()) ?>
        <?php $_subcategories = $_category->getChildrenCategories() ?>

            <?php foreach($_subcategories as $_subcategory): ?>
                <li><a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>"><?php echo $_subcategory->getName() ?></a></li>
            <?php endforeach; ?>

    <?php endforeach; ?>
</ul>

Solution

  • if you have a look at the code getStoreCategories calls a little down the line it uses Mage_Catalog_Model_Resource_Category_Tree. Perhaps you can use it yourself like this:

    <?php
    require_once('app/Mage.php');
    Mage::app();
    $parent = Mage::app()->getStore()->getRootCategoryId();
    $recursionLevel = 2;
    $tree = Mage::getResourceModel('catalog/category_tree');
    /* @var $tree Mage_Catalog_Model_Resource_Category_Tree */
    $nodes = $tree->loadNode($parent)
        ->loadChildren($recursionLevel)
        ->getChildren();
    
    $tree->addCollectionData(null, false, $parent);
    
    foreach ($nodes as $node) {
        /** @var $node Varien_Data_Tree_Node */
        print_r($node->getData()); // first level category data
        foreach ($node->getChildren() as $childNode) {
            print_r($childNode->getData()); // second level category data
        }
    }