How to get subcategories under a custom menu on Ma

2019-09-03 03:42发布

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条回答
Anthone
2楼-- · 2019-09-03 03:59

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>
查看更多
登录 后发表回答