November 25, 2014

Magento Display Categories and Subcategories


Display categories and subcategories in Magento page

    /*Display current store categories*/

    $_helper = Mage::helper('catalog/category');
    $_categories = $_helper->getStoreCategories();

    /*Parent categories*/

    foreach($_categories as $_category) {

      if(!$_category->getIsActive()){
        continue;
      }

      echo $_category->getName();
      echo render_child($_category->getId());
    }
    
    /*Render child categories*/

    function render_child($cid) {
 
     $html = '';
     $_subCategory = Mage::getModel('catalog/category')->load($cid);

     $_subCategories = $_subCategory->getChildrenCategories();

     if (count($_subCategories) > 0){

       $html .= '<ul>';

       foreach($_subCategories as $_subCat){

         if(!$_subCat->getIsActive()){
           continue;
         }
    
         $html .= '<li>';
 
         /*Display first level sub categories*/

         $catUrl = Mage::helper('catalog/category')
                            ->getCategoryUrl($_subCat);

         $html .= "<a href='".$catUrl."'>".$_subCat->getName()."</a>";
  
         /*Display first level sub categories*/

         /*If needed display next level sub categories*/

         $html .= render_child($_subCat->getId()); 
  
         /*If needed display next level sub categories*/

         $html .= '</li>';
      }
   
      $html .= '</ul>';
     }  
     return $html;
  }


Displaying the category and subcategories from the current store. After getting the store categories, check the category is active and output the parent category name.

With the help of
 render_child 
function, check the active subcategories then display first level child elements in list format.

Would like to display all subcategories then call
 render_child 
function, with argument as current category id.
    

No comments:

Post a Comment