Aug 17, 2013
kalpesh

Magento delete empty categories and sub-categories

Remove all empty categories and sub-categories in Magento. When there are empty categories, the website shows empty page in those categories in frontend. Create a file in the magento root, I will name it rmvEmptyCats.php, with following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
require "app/Mage.php";
umask(0);
Mage::app();

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

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

echo 'Empty Categories Deleted!';

Now you can easily run it by navigating to http://loca.lho.st/rmvEmptyCats.php and wait for the message Empty Categories Deleted!

Note that this is going to DELETE those categories with zero product count.

4 Comments

  • Hi,

    I copied the above code, and created an empty php file in notepad and renamed it to what you have – rmvEmptyCats.php

    Uploaded it to my root, went to my host and nothing happens – blank page

    Please advise.

    Thanks

  • Same here!

  • Mage::register(‘isSecureArea’, true);

    add above code to line No. 4, otherwise it will throws exception “Cannot complete this operation from non-admin area.”

    • Hi Priyank,

      I’m getting a 500 error. I’ve added your code to line 4 but it’s still throwing the error:

      Got error ‘PHP message: PHP Fatal error: Uncaught exception ‘Mage_Core_Exception’ with message ‘Cannot complete this operation from non-admin area.’

      Any ideas why?

Leave a comment

 

Welcome to my Blog

Kalpesh MehtaHelping Magento developers in their day-to-day development problems since 2011. Most of the problems and solutions here are my own experiences while working on different projects. Enjoy the blog and don't forget to throw comments and likes/+1's/tweets on posts you like. Thanks for visiting!

Certifications