Magento 2 – delete categories programmatically
In this tutorial I show you how to delete categories programmatically. This is a task you do not use for production systems, but is quite nice if you run tests on your development system. You can also change this code to only delete specific categories.
Magento 2 – delete categories programmatically
For my product import I needed a fast an simple solution to flush my category tree. Every imported product should automatically create its category (or category path) if it does not exist yet during import. To test both option (an empty category tree or a already created category tree), I added a deleteAllCategories function. This function looks like this:
1 2 3 4 5 6 7 8 9 10 | private function deleteAllCategories() { $categoryFactory = $this->_objectManager->get('Magento\Catalog\Model\CategoryFactory'); $newCategory = $categoryFactory->create(); $collection = $newCategory->getCollection(); $this->_registry->register("isSecureArea", true); foreach($collection as $category) { if($category->getId() > 2) $category->delete(); } } |
I’m using a category factory to get a collection of all available categories. In a foreach loop I call $category->delete() for each single category. The only thing to mention is, that is not a good idea to delete category root (has id 2). As I showed in my delete all products programmatically article, it is only possible to delete a category if you declare a secure area.
Things to know
The code above only works if you have injected registry and get object manager singleton. This code shows how this can be done:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class MyClass{ ... protected $_objectManager; protected $_registry; ... public function __construct( \Magento\Framework\Registry $registry, ... ) { ... $this->_registry = $registry; $this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); } ... |
After each change in you construct method with new injections you have to compile you shop again, otherwise you get an empty object. We need \Magento\Framework\Registry to set a secure area for deletion.
Conclusion
It is quite simple to delete all categories programmatically in your Magento 2 shop. I used this function quite often during development. Please note, that if you delete categories, you have to assign all products to the newly created categories again!
I see this is how to set up the function. But how do I execute it?
you can for example create a new PHP script file in you Magento 2 root dir like this and add delete categories code at the end and then run this file from command line or from browser.
I know its a different question, but I think is related. How can I programmatically change the value of ‘parent_id’ in Magento 2?
Hi, I did it with this code
Is there a way to get store_id of category and after that delete?