Thursday, September 6, 2012

Get all categories with tree model in magento


>> This is simple example to get nested category list. You can easily create a left navigation and a drop-down menu with the Retrieved HTML. Follow the code : 

<?php
   $rootCatId = Mage::app()->getStore()->getRootCategoryId();
   $catlistHtml = getTreeCategories($rootCatId, false);
   echo $catlistHtml;

function getTreeCategories($parentId, $isChild){
    $allCats = Mage::getModel('catalog/category')->getCollection()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('is_active','1')
                ->addAttributeToFilter('include_in_menu','1')
                ->addAttributeToFilter('parent_id',array('eq' => $parentId))
                ->addAttributeToSort('position', 'asc');
               
    $class = ($isChild) ? "sub-cat-list" : "cat-list";
    $html .= '<ul class="'.$class.'">';
    foreach($allCats as $category)
    {
        $html .= '<li><span>'.$category->getName()."</span>";
        $subcats = $category->getChildren();
        if($subcats != ''){
            $html .= getTreeCategories($category->getId(), true);
        }
        $html .= '</li>';
    }
    $html .= '</ul>';
    return $html;
}

?>




                                          ***********         Good Luck        **********