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:
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
Leave a comment
Welcome to my Blog
Certifications
Honor
Recognition
Contributions
Categories
- Apache (2)
- ChatGPT (1)
- Domain name (2)
- eCommerce (2)
- htaccess (1)
- Humor (3)
- Instagram API (1)
- jQuery (4)
- JSON (1)
- Linux (10)
- Magento (142)
- Magento admin (58)
- Magento Certification (5)
- Magento error (13)
- Magento frontend (68)
- Magento Imagine (2)
- Magento Interview (5)
- Magento Master (2)
- Magento2 (10)
- Mobile (1)
- MySQL (7)
- OpenAI (1)
- OroCRM (2)
- Performance (2)
- PHP (8)
- Prototype JS (3)
- Security (4)
- Wordpress (3)
- XML (2)
Tag Cloud
500 internal server error admin answers attribute bug category checkbox checkout cookie customer difference domain name EAV error event extension interview invoice jquery linux magento magento2 magento admin magento error magento interview questions magento orm mysql observer order pinterest product products questions redirect register remove script session simplexml to array state status study guide tax url wordpress
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?