Happy Tuesday Folks !
By the following code you will be getting subcategories and all products (product count) form the parent category.
First you have got to insert the Parent ID and then the code below will display you subcategories in it and all products (product count) from the sub categories.
<!--?php /* How will get sub categories and products from parent category in magento?*/ $parentId = 2; // Put parent category Id here $cat = Mage::getModel('catalog/category')--->load($parentId);
$subcatcollection = $cat->getChildren(); // Sub categories id with string
$subcatcollection = explode(",",$subcatcollection);// Will return all sub categories
foreach($subcatcollection as $singlecat): // Find sigle subcategory form loop
$fcat = Mage::getModel('catalog/category')->load($singlecat); //Single category information
if($fcat->getIsActive()): // Check Category is Active
$_proCollection = Mage::getResourceModel('catalog/product_collection')
->addCategoryFilter($fcat)
->setOrder('name', 'ASC'); //Sort by Product Name
$_collectionSize = count($_proCollection); //Will return number of products category.
?>
<a title="<?php echo $fcat->getName(); ?>" href="<?php echo $this->getUrl().$fcat->getUrl_path(); ?>">
<!--?php echo $fcat--->getName(); ?>
</a><!-- Show Categoy Name & Url. -->
<!--?php foreach ($_proCollection AS $ffproduct): $cur_fproduct = Mage::getModel('catalog/product')--->load($ffproduct->getId());
//product all information.
if($cur_fproduct->getVisibility()!=1):
?>
<a href="<?php echo $this->getUrl().$cur_fproduct->getUrl_path(); ?>">
<!--?php echo $cur_fproduct--->getName(); ?>
</a> <!-- Show Product Name & Url. -->
<!--?php endif; endforeach; ?-->
<!--?php endif; ?-->
<!--?php endforeach; ?-->
Thanks and feel free to share your comments.
2 replies on “Get sub categories and product count in magento”
Is there a way to sort the subcategories when you getChildren?
Line # 6 $subcatcollection = $cat->getChildren();
thanks!
Hello Angela,
You can sort subcategories by below code:
Line 6# $subcatcollection = $cat->setOrder(‘name’, ‘ASC’)->getChildren();
Thanks