Magento – Remove empty categories from magento menu

category-tree

(Apologies for posting this here, and if people think this should be deleted, please do.

I posted this question on stackoverflow, having completely forgotten this forum, which of course is more appropriate for a Magento question. I'd prefer to move it here but… how?!

In order to keep only one version, I've posted the link to it here.

https://stackoverflow.com/questions/22822997/remove-empty-categories-from-magento-menu

Btw, I found an answer although I'm sure it can be improved.)

I want my main menu to not include any categories that are empty. I've done this for the layered navigation very easily in the relevant phtml file by using

$_category->getProductCount(). 

However, for the navigation menu, I'm finding it impossible to do this as easily (I have seen the Prattski example but it does seem rather OTT).

The main menu seems to be built in Mage_Page_Block_Html_Topmenu.php, specifically in the function _getHtml. This gets all the children in the menu and if I try something like $child->getId(), I get something like category-node-36.

It doesn't seem like I'm too far from being able to use getProductCount() and so test if it's more than zero.

Is it possible to do this? Can somebody point me to how?

If I can, I'll extend the class with my version.

Best Answer

cronjob

If you ask me, filtering the categories on the menu is bad for the performance and deactivating them is a better idea.

So my suggestion is to implement a cronjob that checks all categories and child categories for products and if there are no, set the status to disabled.

And implement an observer which does the same for only one category on the event catalog_category_save_before

while loading collection

You can implement an observer which listens on catalog_category_collection_load_before and add a setLoadProductCount(true) to the collection, then you can use $category->getProductCount() in the menu template... Ah, btw when you filter the categories, the counts do mismatch, maybe this is a problem somewhere, e.g. while paging (what you don't do) this makes problems if you show fewer items than you selected.

I think you have to change the block for the top menu. I would change the reference in the layout.xml instead of rewriting the block, but this is up to you, then change _getHtml and immediately in the foreach just check the count and continue; when 0

Related Topic