Magento: Display Only If There Are Products In The Category

Magento Icon

This is a more difficult post to title – but I think that should do it. Here was my need today: We’ve got some navigational links in the header, and there are two categories “Sale Items” and “Internet Only” that should show up as links ONLY if there are products in those categories – otherwise, they shouldn’t be there (no need to have a link to a category with no products in it).

The Solution

There’s a quick’n'easy code line that you can pass in a category id to, and it will return how many products are in that category:

Mage::getModel('catalog/category')->load(198)->getProductCount()

So – I got the category IDs from the admin and I created the following code to check the count – and display the link only if there are products in that category:

<?php
    $sale_count = Mage::getModel('catalog/category')->load(198)->getProductCount();
    if ($sale_count > 0) : ?>
        <li class="sale"><a href="/sale/">Sale Items</a></li>
<?php
    endif;
    $internet_count = Mage::getModel('catalog/category')->load(200)->getProductCount();
    if ($internet_count > 0) : ?>
        <li class="internet"><a href="/internet-only/">Internet Only</a></li>
<?php
    endif;
?>

Hopefully you can find that useful if you need it!

This entry was posted in Magento. Bookmark the permalink.

3 Responses to Magento: Display Only If There Are Products In The Category

  1. Bimal says:

    Thank you..
    You don’t need the categoryID.. It’s also dynamic :
    Mage::getModel(‘catalog/category’)->load($this->htmlEscape($_category->getId()))

  2. Dan says:

    Thanks for the tip mate, very useful for my deals website I am building http://discountdeals.com.au where I needed to count the current deals,

    Dan

  3. Vangilsweb says:

    We use the Easy Catalog Images extension. Which file do we have to edit with this code to automatically hide empty categories on anchor pages?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">