B-219 Sec-55 Noida, India
+918010221733

Creating Recursive Menu in Magento

In order to create the menu a function need to be added. The function that will receive the ID of the parent (main) categories as an argument and will be displaying child categories. Also the function should check presence of the sub-categories each time a child category is called. 

Here’s the example of the ‘recursive’ function:
   
<?php
$rootСatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel(‘catalog/category’)->getCategories($rootСatId);
function  get_categories($categories) {
    $tree= ‘<ul>’;
    foreach($categories as $category) {
        $cat = Mage::getModel(‘catalog/category’)->load($category->getId());
        $tree .= ‘<li>’.
        ‘<a href=”‘ . Mage::getUrl($cat->getUrlPath()). ‘”>’ .
            $category->getName() . “(” . $cat->getProductCount(). “)</a>n”;
        if($category->hasChildren()) {
            $children = Mage::getModel(‘catalog/category’)->getCategories($category->getId());
             $tree .=  get_categories($children);
            }
         $tree .= ‘</li>’;
    }
    return  $tree . ‘</ul>’;
}
echo  get_categories($categories); ?>

To get the parent category ID and all its child categories, use this script:
   
$rootСatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel(‘catalog/category’)->getCategories($rootСatId);

In function: get_categories the list of the categories’ links, the titles and products quantities in each of it, is formed.

Then the presence of the sub-categories should be checked. If there are some we should call function: get_categories with the current category ID as a parameter.
   
if($category->hasChildren()) {
$children = Mage::getModel(‘catalog/category’)
->getCategories($category->getId());
$tree .=  get_categories($children);
     }

This circle could be repeated many times until the full list of the categories is formed.  And that’s it.

(Visited 60 times, 1 visits today)

Leave a reply

You must be logged in to post a comment.