4

I have some code that I'm using to show Categories and Sub-Categories in my Magento webstore. Currently, each category is listed with the amount of products within that category displayed. Eg:

Shop (parent category)

  • Category 1 (12)
  • Category 2 (3)
  • Category 3 (0)
  • Category 4 (50)

The issue I'm having is that the product amounts when in the 'Shop' category are all correct. However, when I visit a child category (EG. Category 2), the product amounts now show all the disabled products as well. EG:

Shop (parent category)

  • Category 1 (16)
  • Category 2 (5)
  • Category 3 (1)
  • Category 4 (52)

The code I am using for the sidebar category list is as follows:

<div class="block">
<div class="block-title">
    <strong><span>Categories</span></strong>
</div>
<div class="block-content">
    <dl id="narrow-by-list2">
        <dt><a class="shop-link" href="/shop.html"><?php echo $this->__('Shop') ?></a></dt>
        <dd>
            <ol>
            <?php foreach ($_categories as $_category): ?>
                <?php if($_category->getIsActive()): ?>
                <li>
                    <a href="<?php echo $this->getCategoryUrl($_category) ?>"<?php if ($this->isCategoryActive($_category)): ?> class="current"<?php endif; ?>><?php echo $this->escapeHtml($_category->getName()) ?></a> (<?php echo $_category->getProductCount() ?>)
                </li>
                <?php endif; ?>
            <?php endforeach ?>
            </ol>
        </dd>
    </dl>
    <script type="text/javascript">decorateDataList('narrow-by-list2')</script>
</div>

Any help on this issue would be greatly appreciated!

1 Answer 1

0

The getProductCount method does not exclude the disabled products.
You can take a look at it in Mage_Catalog_Model_Resource_Category::getProductCount().

You can try this instead of $category->getProductCount()

$collection = Mage::getModel('catalog/product')->getCollection()
          ->addCategoryFilter($category);
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);

$count = $collection->count();

Then you can use the $count variable in your code.

3
  • Like so? < ? php echo $count; ? >
    – Rob
    Nov 12, 2015 at 22:38
  • Yes. Like that.
    – Marius
    Nov 13, 2015 at 6:12
  • I'm getting the following error when using the above code. "Fatal error: Call to a member function getId() on a non-object in /home/sirenvisual/public_html/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php on line 719". Any ideas?
    – Rob
    Nov 20, 2015 at 2:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.