How to get subcategories under a custom menu on Magento

泪湿孤枕 提交于 2019-12-11 20:38:11

问题


I have successfully created a custom drop-down-menu for each specific category I needed but one of them needs to load the subcategory within a subcategory and I can't get it to work.

The working code without the "subcategory within a subcategory" is the following but I need to find out how to add the 3rd level on this code.

 <!-- Vending -->
 <?php $main = Mage::getModel('catalog/category')->load(355) ?>
 <li class="eight"><a href="<?php echo $main->getUrl() ?>"><?php echo $main->getName(); ?></a>
 <?php $children = Mage::getModel('catalog/category')->getCategories(355); ?>
 <ul class="nav_static">
 <?php foreach ($children as $category): ?>
 <li>
 <a href="<?php echo $category->getRequestPath(); ?>">
 <?php echo $category->getName(); ?>
 </a>
 </li>
 <?php endforeach; ?>
 </ul>
 </li>
 <!-- END - Vending -->

回答1:


Well, as I have suggested in https://stackoverflow.com/a/14586422/653867 you have to load a category object for your second level categories:

$cat = Mage::getModel('catalog/category')->load($category->getEntityId());

then you can access its children by executing

$children = $cat->getChildrenCategories();

The $children variable is a collection of type Mage_Catalog_Model_Resource_Category_Collection, and you can iterate through it to output the next level categories

I think, your code can be improved a bit if you called getChildrenCategories() on your $main in the first place. You wouldn't have to load every child in a loop, which can be performance punishing. Instead use this (and it can actually be improved even further with recursive calls, but such setup would include creating extra blocks, which might be too much hassle for this particular case):

 <?php $main = Mage::getModel('catalog/category')->load(355) ?>
 <li class="eight"><a href="<?php echo $main->getUrl() ?>"><?php echo $main->getName(); ?></a>
 <?php $children = $main->getChildrenCategories(); ?>
 <ul class="nav_static">
 <?php foreach ($children as $category): ?>
 <li>
 <a href="<?php echo $category->getUrl(); ?>">
 <?php echo $category->getName();

 $subCategories = $category->getChildrenCategories();
 foreach ($subCategories as $subCat) {
 /**
  *your code to output the next level categories
  */
 }
 ?>
 </a>
 </li>
 <?php endforeach; ?>
 </ul>
 </li>


来源:https://stackoverflow.com/questions/14588444/how-to-get-subcategories-under-a-custom-menu-on-magento

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!