Saturday, December 1, 2012

Magento - Get all Categories and Subcategories

It is not such a typical task. Here is the code to get all Categories and Subcategories in Magento -


<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry('current_category') ?>
<?php if (count($_categories) > 0): ?>
<div id="tabs-1">
    <ul id="tree1">
        <?php foreach($_categories as $_category): ?>
            <li>
                    <input type="checkbox" value="<?php echo $_category->getId() ?>"><label><?php echo $_category->getName() ?></label>
                <?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
                <?php $_subcategories = $_category->getChildrenCategories() ?>
                <?php if (count($_subcategories) > 0): ?>
                    <ul>
                        <?php foreach($_subcategories as $_subcategory): ?>
                            <li>
                                <input type="checkbox" value="<?php echo $_subcategory->getId() ?>"><label><?php echo $_subcategory->getName() ?></label>
<?php $_category = Mage::getModel('catalog/category')->load($_subcategory->getId()) ?>
               <?php $_subsubcategories = $_subcategory->getChildrenCategories() ?>
               <?php if (count($_subsubcategories) > 0): ?>
                   <ul>
                       <?php foreach($_subsubcategories as $_subsubcategory): ?>
                           <li>
                               <input type="checkbox" value="<?php echo $_subsubcategory->getId() ?>"><label><?php echo $_subsubcategory->getName() ?></label>
                           </li>
                       <?php endforeach; ?>
                   </ul>
               <?php endif; ?>

                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </li>
        <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

Enjoy!! :-)