Create Category Tree in Magento

July 19th, 2012 by jitendra | 4 comments

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.

  1. <?php
  2. function CreateCategoryTree($categories)
  3. {
  4. $html = ‘<ul>’;
  5. foreach($categories as $category)
  6. {
  7. $categoryUrl = Mage::getModel(‘catalog/category’)->load($category->getEntityId())->getUrl();
  8. $html .= ‘<li><a href=”‘ .$categoryUrl. ‘”>’ . $category->getName() . “</a>\n”;
  9. if($category->hasChildren())
  10. {
  11. $children = Mage::getModel(‘catalog/category’)->getCategories($category->entity_id);
  12. $html .= CreateCategoryTree ($children);
  13. }
  14. $html .= ‘</li>’;
  15. }
  16. return $html . ‘</ul>’;
  17. }

Make a object of Mage_Catalog_Block_Navigation as given below in your page where you want to generate a tree:

  1. <?php
  2. $Mage_Catalog_Block_Navigation = new Mage_Catalog_Block_Navigation();
  3. $categories = $Mage_Catalog_Block_Navigation->getStoreCategories();
  4. $cat = Mage::helper(catalog);
  5. echo $cat->CreateCategoryTree($categories);
  6. ?>

Please add the following CSS in your style sheet to make a tree.

  1. ul.sitemap
  2. {
  3. }
  4. ul.sitemap li
  5. {
  6. padding: 3px 0px 3px 0px;
  7. }
  8. ul.sitemap li span
  9. {
  10. text-transform: uppercase;
  11. margin: 10px 0px 10px 0px;
  12. }

 

The Author

Jitendra Kumar is a Sr. Software developer, an author and recreational software developer specializing in web standards. He has extensive knowledge of Core PHP, PHP Framworks, e-commerce tools, social media sites, gaming, networking and front-end development (JavaScript, Jquery, Ajax, HTML & CSS). If you’d like to connect with him, follow him on : @Twitter.

 

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

 

 

  1. July 19th, 2012 at 05:16 | #1

    This function could be very useful to some of our payment gateway clients; thank you for sharing the information.

    Kind regards,
    The eWAY Team

  2. September 26th, 2012 at 20:11 | #2

    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

  3. gtalk for android
    October 13th, 2012 at 23:19 | #3

    I like reading an article that will make men and women think.
    Also, many thanks for permitting me to comment!

  4. November 3rd, 2012 at 05:55 | #4

    i am new to magento, can i know where to create object $Mage_Catalog_Block_Navigation

  1. No trackbacks yet.