Create Category Tree in Magento
In magento sometimes we need to create tree menu of all the categories and subcategories.
Create a function in to app/code/core/Mage/Catalog/Helper/Data.php
Function recursively call itself and generates a tree.
- <?php
- function CreateCategoryTree($categories)
- {
- $html = ‘<ul>’;
- foreach($categories as $category)
- {
- $categoryUrl = Mage::getModel(‘catalog/category’)->load($category->getEntityId())->getUrl();
- $html .= ‘<li><a href=”‘ .$categoryUrl. ‘”>’ . $category->getName() . “</a>\n”;
- if($category->hasChildren())
- {
- $children = Mage::getModel(‘catalog/category’)->getCategories($category->entity_id);
- $html .= CreateCategoryTree ($children);
- }
- $html .= ‘</li>’;
- }
- return $html . ‘</ul>’;
- }
Make a object of Mage_Catalog_Block_Navigation as given below in your page where you want to generate a tree:
- <?php
- $Mage_Catalog_Block_Navigation = new Mage_Catalog_Block_Navigation();
- $categories = $Mage_Catalog_Block_Navigation->getStoreCategories();
- $cat = Mage::helper(catalog);
- echo $cat->CreateCategoryTree($categories);
- ?>
Please add the following CSS in your style sheet to make a tree.
- ul.sitemap
- {
- }
- ul.sitemap li
- {
- padding: 3px 0px 3px 0px;
- }
- ul.sitemap li span
- {
- text-transform: uppercase;
- margin: 10px 0px 10px 0px;
- }
The Author

Follow @phpzag

This function could be very useful to some of our payment gateway clients; thank you for sharing the information.
Kind regards,
The eWAY Team
Good ?I should definitely pronounce, impressed with your site. I had no trouble navigating through all tabs as well as related information ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your customer to communicate. Nice task.
http://uggbootsukstore1.webeden.co.uk
I like reading an article that will make men and women think.
Also, many thanks for permitting me to comment!
i am new to magento, can i know where to create object $Mage_Catalog_Block_Navigation