Magento – Count of viewable products in a category

categorycollection-filteringcollection;productproduct-collection

Is there any pre-defined way in Magento to get all "viewable" products ?

I want to calculate total count of the products that are viewable in the category page. I know that in each category page, there is a current_category registry that we can use to calculate the number of products in the current category but I want a way to do it for all categories and store the results in a table for each category in each website-store.

The getProductCount not giving the exact number of viewable-only products also simple getProductCollection or similar functions don't return correct results.

Of course viewable products should be enabled, visible, In stock and with qty > 0 and for configurable products there might be at least 1 associated product that have above conditions in the current store view. But there might be stores that show Out of stock products also and label with "Out of Stock".

I want to calculate the exact number shown in category page, how can I do that ? Is there any easy way for this ? Or I need to write complex queries and retrieve data directly from the database?

i.e: I want the exact number calculated here in category page:

enter image description here

Best Answer

Yes, use this code

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToFilter('visibility', 4);

It will get you the visible products, since 4 means Catalog and search visibility. You can combine that with this to add stock check

Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($products);
Related Topic