Only active product count on Magento Category
11,695
Solution 1
you need check active filter acondition and for this you can use below code
$products = Mage::getModel('catalog/category')->load($category->getId())
->getProductCollection()
->addAttributeToSelect('entity_id')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4);
echo $products->count();
Solution 2
Without any regard to Magento programming conventions, that piece of code should look like this:
<?php
$cats = Mage::getModel('catalog/category')->load(3)->getChildrenCategories();
$collection = Mage::getModel('catalog/product')->getCollection();
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);
?>
<ul>
<?php foreach($cats as $category): ?>
<?php $count = $collection->addCategoryFilter($category)->getSize(); ?>
<li>
<a href="<?php echo $category->getUrl() ?>"><?php echo $category->getName() ?>(<?php echo $count ?>)</a>
</li>
<?php endforeach; ?>
</ul>
But do the world a favor and organize the code properly.
Author by
Shamim Ahmed
Updated on June 08, 2022Comments
-
Shamim Ahmed almost 2 years
I am trying to display the number of products in each category, using this code to I want to display subcategories of category
id:3
. It is showing but it included disabled and invisible products.<?php $cats = Mage::getModel('catalog/category')->load(3)->getChildrenCategories(); ?> <ul> <?php foreach($cats as $category): ?> <li> <a href="<?php echo $category->getUrl() ?>"><?php echo $category->getName() ?>(<?php echo $category->getProductCount(); ?>)</a> </li> <?php endforeach; ?> </ul>
Is there any good solution so that I can get the exact count of categories that are Enabled and active.
-
Shamim Ahmed almost 11 yearsIt is displaying correctly only for first subcategory, and first subcategory product count is repeating for all other subcategory also please check awesomescreenshot.com/0e31cd034f
-
srgb almost 11 yearsAlternatively, you can use
$category->getProductCollection()
in foreach, and pass it through the Visibility filters, but it will have a bit larger impact on server in that case. Basically, the trick is to pass the collections through the two Visibility filters. Try to find a way not to load a product collection in each loop. -
Michel Gokan Khan almost 10 yearsIt won't give the exact number of products visible in a category. there are a lot more conditions for configurable products and also simple in stock products.