Hide categories without products in magento

The easiest way to do this is to only rewrite the Mage_Catalog_Block_Navigation block:

In the method _renderCategoryMenuItemHtml() you want to replace the loop

path: app/code/local/module folder

foreach ($children as $child) {
    if ($child->getIsActive()) {
        $activeChildren[] = $child;
    }
}

with this:

foreach ($children as $child) {
        if ($child->getIsActive() && $this->_hasProducts($child->entity_id)) {
            $activeChildren[] = $child;
        }
    }

and similarly in the method renderCategoriesMenuHtml()
replace the code

foreach ($this->getStoreCategories() as $child) {
        if ($child->getIsActive()) {
            $activeCategories[] = $child;
        }
    }

with this:

foreach ($this->getStoreCategories() as $child) {
        if ($child->getIsActive() && $this->_hasProducts($child->entity_id)) {
            $activeCategories[] = $child;
        }
    }

Finally add the method we were just using in our code:

protected function _hasProducts($category_id) {
    $products = Mage::getModel('catalog/category')->load($category_id)
        ->getProductCollection()
        ->addAttributeToSelect('entity_id')
        ->addAttributeToFilter('status', 1)
        ->addAttributeToFilter('visibility', 4);
    return ( $products->count() > 0 )  ? true : false;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s