Reputation: 931
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.
Upvotes: 4
Views: 12054
Reputation: 241
Loading collection and using multiple attribute filter is not a proper way and this won't filter associated product and it's stock levels.
This piece of code with do all together,
$categoryId = 32; // Replace with your category
$category = Mage::getModel('catalog/category')
->setStoreId(Mage::app()->getStore()->getId())
->load($categoryId);
Mage::register('current_category', $category);
$products = Mage::getSingleton('catalog/layer')->getProductCollection();
echo $products->getSize();
Upvotes: 0
Reputation: 632
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();
Upvotes: 3
Reputation: 5193
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.
Upvotes: 1