When it comes to website navigation, menu behaves like a roadmap to various informative places of the website. Visitors will only stay on website if the menu and navigation is clear and this will be considered as a good user experience. Recently I have been working on my client’s site where he has multiple category structure for each product. We had to custom code to show it in website menu. The main reason behind this was to provide users the thing he needed directly from the home page menu with lesser clicks. This really works well when it comes to providing better user experience and easy navigation to web users.
If you also want to create categories tree structure in Magento, follow this code and paste at the proper place where you want to show the tree structure and show nested categories.
Here is the code to create categories tree structure in Magento programmatically
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
//CODE FOR MENU START function renderCategoriesTree($category) { $children = Mage::getModel('catalog/category')->load($category->getId()); if($children->getData('children_count')) { $cl='menu-item-has-children menu-parent-item'; } else { $cl=''; } echo '<li class="'.$cl.'">'; echo "<a href='".Mage::getBaseUrl().$children->getUrlPath()."'>"; echo '<span>'.$children->getName().'</span>'; echo "</a>"; if($children->getData('children_count')) { echo "<ul>"; $childr = Mage::getModel('catalog/category')->getCategories($category->getId()); foreach ($childr as $child) { renderCategoriesTree($child); } echo "</ul>"; } echo '</li>'; } $categories = Mage::getModel('catalog/category') ->getCollection() ->addAttributeToSelect('*') ->addIsActiveFilter() ->addAttributeToFilter('include_in_menu','1') ->addAttributeToFilter('level','2'); foreach($categories as $item) { renderCategoriesTree($item); } //CODE FOR MENU END |
Adding above custom code in Magento will create a categories tree structure like shown below.
Let me know through commenting if you have any confusion or query regarding this. Your suggestions & feedback are always welcomed. till than, Happy Coding!