Generate Category Tree Recursively

In this blog we will see how generate a category tree, recursively showing all categories and sub categories.

The code is given below, will explain the code line by line

$rootcatId= Mage::app()->getStore()->getRootCategoryId(); 
$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);
function  get_categories($categories) {
    $array= '<ul>';
    foreach($categories as $category) {
       	$cat = Mage::getModel('catalog/category')->load($category->getId());
    	$count = $cat->getProductCount();
        $array .= '<li>'.
        '<a href="' . Mage::getUrl($cat->getUrlPath()). '">' . 
                  $category->getName() . "(".$count.")</a>\n";
        if($category->hasChildren()) {
            $children = Mage::getModel('catalog/category')->getCategories($category->getId());
             $array .=  get_categories($children);
         $array .= '</li>';
    return  $array . '</ul>';
echo  get_categories($categories); ?>

Explanation of the code step by step:

  $rootcatId= Mage::app()->getStore()->getRootCategoryId(); 

This function gives return the Root Catalog Id of your current store. Usually the value is 2 but its always better to use this function.

$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);

This function returns all sub categories of the parent category. This function is defined in Mage_Catalog_Model_Category. the definition is

     * Retrieve categories by parent
     * @param int $parent
     * @param int $recursionLevel
     * @param bool $sorted
     * @param bool $asCollection
     * @param bool $toLoad
     * @return mixed
    public function getCategories($parent, $recursionLevel = 0, $sorted=false, $asCollection=false, $toLoad=true);
function  get_categories($categories) { //This is the recursive function created and here we pass the a collection of categories.
$array= '<ul>';  //$array is a variable to store all the category detail .
foreach($categories as $category) {
     	$cat = Mage::getModel('catalog/category')->load($category->getId());
        $count = $cat->getProductCount(); //$count the total no of products in the category
        $array .= '<li>'.'<a href="' . Mage::getUrl($cat->getUrlPath()). '">' . $category->getName() . "(".$count.")</a>\n"; //In this line we get an a link for the product and product count of that category
        if($category->hasChildren()) {  if category has children or not. If yes then it proceed in inside loop.
        	 $children = Mage::getModel('catalog/category')->getCategories($category-> getId()); // $children get a list of all subcategories
            $array .=  get_categories($children); //recursive call the get_categories function again.
         $array .= '</li>';
    return  $array . '</ul>';
echo  get_categories($categories); //echo all categories in the website, with number of products

You can use your own css and javascript to design the html generated.

  • Prashant

    Excellent I Want More Blog like This….Its very Useful..Please request Share your Knowledge with other…

  • Naresh Tank

    It’s very use full for me .keep it up..

  • robgt

    I’ve used this code, and for the most part it works – but there is an issue for me. The lowest level of the menu (4 levels deep) doesn’;t create the link to the page correctly. Any idea why?

    • Hi Robgt, I found this post and I have the same problem too: the 4 levels link not working… You managed to find a solution?

  • Jignesh Thummar

    Nice work Nutan 

  • Bharanidharan K

    hi i have one problem

    i create news and event modules and i set as menu links every thing is fine, but there is a loading time difference between other menus and my own module menus, other menu links are loaded very fast when compare to my own module menu.,

    can you help me

  • TuanBachVan

    No error, thank very much. 

  • disqus_0FDyLLBqI9

    it’s full of error cant help me

  • Olivier Varrot

    Hello, how can I change the storeId to view a different tree ?
    Thank you

  • John
  • bala

    ya it worked for me…but i have to display in dropdown like if we click the main category means the subcategory should be displayed else it should hide the subcategory.Pls help me. Thanks in advance 🙂

  • Naresh


    I am new to the magento i am also trying to get tree structure categories ?

    which location i have to place this code ?

    Thank You

  • Kamlekar Venkateshwar

    Great article Nutan.. working fine here 🙂

  • Dhaval Hingrajia


  • Afmatenterprise Kakinada

    beautiful just beautiful . works like charm 🙂 made my day