Magento - get a parent category and all sub-sub-categories
Solution 1
Figured it out:
$cat = Mage::getModel('catalog/category')->load(24);
$subcats = $cat->getChildren();
foreach(explode(',',$subcats) as $subCatid)
{
$_category = Mage::getModel('catalog/category')->load($subCatid);
if($_category->getIsActive()) {
$sub_cat = Mage::getModel('catalog/category')->load($_category->getId());
$sub_subcats = $sub_cat->getChildren();
foreach(explode(',',$sub_subcats) as $sub_subCatid)
{
$_sub_category = Mage::getModel('catalog/category')->load($sub_subCatid);
if($_sub_category->getIsActive()) {
echo '<li class="sub_cat"><a href="'.$_sub_category->getURL().'" title="View the products for the "'.$_sub_category->getName().'" category">'.$_sub_category->getName().'</a></li>';
}
}
}
}
Thanks for looking!
Solution 2
All answers so far load children categories in a loop which is generally bad practice and causes execution of many SQL queries where a single one would suffice.
Performant Single Query Solution:
Let $parentCategory
be your Main Category, then this collection will load all subcategories, two levels below:
$subcategoryCollection = Mage::getModel('catalog/category')
->getCollection()
->addFieldToFilter('level', $parentCategory->getLevel() + 2)
->addFieldToFilter('path', ['like' => $parentCategory->getData('path') . '/%']);
The path
field contains the category id prefixed with all ancestor ids in the form 1/2/3
. Database wise it is a column in catalog_category_entity
that has an index, so comparison like this has no performance issues.
Solution 3
I have developed a recursive function to get all children of a category
$categoryObject = Mage::getModel('catalog/category')->load(CATID);
$children = MODEL_OBJECT->getChildCategories($categoryObject);
// IN MODLE FILE
public $_catIds = array();
public function getChildCategories($categoryObject){
$categories = $categoryObject->getChildrenCategories();
foreach ($categories as $catgory){
if($catgory->hasChildren()){
$this->getChildCategories($catgory);
}
$this->_catIds[] = $catgory->getId();
}
return $this->_catIds;
}
Hope this will help you.
Comments
-
terrid25 almost 2 years
I have a single category, that has 2 subcategories. Within each of these categories, are 5 subcategories.
Is there a way to get a list of all of these 10 sub-sub-categories?
Thanks
EDIT:
Something like this:
Main Category Sub_Cat_1 Cat_1 Cat_2 Cat_3 Sub_Cat_2 Cat_4 Cat_5 Cat_6 Wanting output like: Cat_1 Cat_2 Cat_3 Cat_4 Cat_5 Cat_6
Thanks
-
Andreas von Studnitz over 9 yearsYou should never use a "load()" inside a loop.
-
Anthony over 8 years'/%' - is correct rather than '%'. For ../8 and ../868 gets wrong result in the previous version.
-
Andrew Lynch almost 8 yearsWhen looping through the results, why does getUrl() work but getName() not. What is the best way to get the name of each subcategory?
-
Fabian Schmengler almost 8 yearsIf you don't see the name, try to add
addAttributeToSelect("name")
after getCollection().