4

I want to implement something that would delete the empty categories and sub categories if there are no products in them.

There may be 100s of categories.So I don't want to use backend for this.

I am in trouble please help me.

I am referring this link Hide Empty Categories but this is only hiding parent categories from navigation bar even if it's sub categories have products in them.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mukesh
  • 7,630
  • 21
  • 105
  • 159

1 Answers1

10

Here is one way to delete empty categories...

$categoryCollection = Mage::getModel('catalog/category')->getCollection()
    ->addFieldToFilter('level', array('gteq' => 2))
;

foreach($categoryCollection as $category) {
    if ($category->getProductCount() === 0) {
        $category->delete();
    }
}

This will delete the categories - not simply hide them


EDIT

To answer the following posted in a comment:

"Could you please share a link of some tutorial or weblink.I am weak in creating custom modules". 

see here

You would be better just creating a script for this simple task. Here is a nice resource to explain how to bootstrap Magento for your script to run.

Community
  • 1
  • 1
Drew Hunter
  • 10,136
  • 2
  • 40
  • 49
  • Could you please share a link of some tutorial or weblink.I am weak in creating custom modules. – Mukesh Aug 31 '12 at 10:27
  • Could you please tell me how and where to implement this code. – Mukesh Aug 31 '12 at 14:10
  • I am referring this link "http://prattski.com/2011/10/06/magento-module-hide-empty-categories/" but this is only hiding parent categories from navigation bar even if it's sub categories have products in them. – Mukesh Sep 01 '12 at 07:12
  • @Muk: If this is one time business, Why you want to create a module ? just create the script file in root and execute then remove it. Make your life lighter. – Gowri Sep 01 '12 at 07:51
  • @Muk - In my answer there are two links at the bottom: the first is a tutorial on how to create a custom module. The second will show you how to bootstrap Magento, which you can use to build a script. Its up to you which method to choose. – Drew Hunter Sep 01 '12 at 09:06
  • @Drew Hunter: i have experiment your code, Its trying to delete Magento root directory. And throw me the error. – Gowri Sep 03 '12 at 10:49
  • @muk If I have the category ids .How can I find the subcategories and product count for that? – Mukesh Sep 03 '12 at 11:18
  • @gowri - i have updated the answer for you. Simply filter the collection – Drew Hunter Sep 03 '12 at 11:46
  • @Muk - this is becoming a completely different question. You would be best addressing your new queries in a new question – Drew Hunter Sep 03 '12 at 14:21