How to show only Visible/Active Products in Product Count

Magento’s integrated function getProductCount() also counts invisible/inactive products. If your theme displays product counts next to each category (e.g. in the top menu or category blocks), this can be very confusing for your customer.

If your category product count shows 10 products, but 6 are set to invisible. Your customer wil end up very disappointed to see only 4 products in the product list.

Today I will show you how to display only visible/active products in your Magento theme’s category product count.

getProductCount uses the getData-method to retrieve the product_count value from Magento’s database. The problem with this is that Magento also takes invisible or inactive products into consideration when calculating the product count for a category.

To adjust this behaviour we need to add filters to the product collection as follows:

<?php
$collection = $_category->getProductCollection();
$collection->setVisibility(array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH, Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG));
$collection->addFieldToFilter('status',Mage_Catalog_Model_Product_Status::STATUS_ENABLED);

If your theme uses a different variable name for the $_category, then replace it with the name your theme uses. You can then return the correct product count by using the $collection->count(). E.g. if you’d want to display the adjusted category count, you would add the following line of code in the right place of your theme’s file:

<?php echo $collection->count(); ?>

That’s it! Your theme will now only display visible/active products in category product count. This code can be used anywhere in your template.

  • The Wait is Over.

    Get the Newsletter you've always wanted, now!

    Sign up to receive Biweekly, Free Optimization Tips for WordPress.

    No spam. I promise.

  • Daan van den Bergh

    Daan van den Bergh is a carefully seasoned web developer. His methods consist of thinly slicing your website’s beef and serve you with a platter of the best performance carpaccio on a bed of rocket — the only thing he’s more passionate about is food. Hire him at ffwp.dev.

    1 thought on “How to show only Visible/Active Products in Product Count”

    1. Hello sir,
      I want to show only active product on php row table after sale. For example if i have 50 product from it 1 item sale then it be shown as 49 are visible.

      Waiting for your reply
      Akhil

      Reply

    Leave a Comment

    This site uses Akismet to reduce spam. Learn how your comment data is processed.