This article shows how to get sub categories of a particular category and the number of products (product count) present in the sub categories.
Suppose, you have a category named Furniture. The sub categories under Furniture are Living Room and Bedroom. Now, you want to show the sub categories under Funiture and the products associated with the sub categories (Living Room and Bedroom).
Furniture
– Living Room (4)
– Bedroom (2)
/**
* get current category
*/
$currCat = Mage::registry('current_category');
/**
* get sub categories of current category
*/
$collection = Mage::getModel('catalog/category')->getCategories($currCat->getEntityId());
/**
* looping through sub categories
* only showing active sub categories ($cat->getIsActive())
*/
foreach($collection as $cat) {
if($cat->getIsActive()) {
$category = Mage::getModel('catalog/category')->load($cat->getEntityId());
/**
* getting product collection for a particular category
* applying status and visibility filter to the product collection
* i.e. only fetching visible and enabled products
*/
$prodCollection = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter($category);
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($prodCollection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($prodCollection);
?>
<a href="<?php echo $category->getUrl() ?>"><?php echo $category->getName() ?></a> (<?php echo $prodCollection->count() ?>)<br/>
<?php
}
}
Thanks.