To get a collection of subcategories of a given category $parentCategory
, use:
$subcategoryCollection = Mage::getModel('catalog/category')
->getCollection()
->addFieldToFilter('level', $parentCategory->getLevel() + 1) // remove this to go deeper
->addFieldToFilter('path', ['like' => $parentCategory->getData('path') . '%']);
(as described here: https://stackoverflow.com/q/5564647/664108)
As noted in the code comment above, you can use the level
filter to specify how deep you want to recurse into subcategories. To get subcategories and sub-sub-categories but not sub-sub-subcategories, use this:
->addFieldToFilter('level', ['lte' => $parentCategory->getLevel() + 2])
(lte
stands for less than or equal)
If you want to show the categories sorted by parent like this
1
1.1
1.1.1
1.1.2
1.2 2
2.1
add this line:
$subcategoryCollection->setOrder('path', Varien_Data_Collection_Db::SORT_ORDER_ASC);
Depending on what data you need to display, select the attributes to select:
$subcategoryCollection->addAttributeToSelect(['name', 'description', 'image']);
You can always select all attributes with addAttributeToSelect('*')
instead, but I don't recommend it because it results in unneccessary queries to the EAV tables.
Then you can foreach
over $subcategoryCollection
and display the subcategories however you wish.
Example template:
<?php foreach ($subcategoryCollection as $category): ?>
<a href="<?php echo $category->getUrl() ?>">
<?php echo $this->htmlEscape($category->getName()) ?>
</a>
<?php endforeach; ?>