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
<?php $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.