I would like to delete categories and sub categories pro-grammatically in magneto 2.
Please suggest me proper code for it.
To test both option (an empty category tree or a already created category tree), I added a deleteAllCategories function.
This function looks like this:
<?php
...
use Magento\Catalog\Model\CategoryFactory;
use Magento\Framework\Registry;
/**
* Class CategoryDeletion
* @package Project\Catalog
*/
class CategoryDeletion
{
/** @var Registry $registry */
private $registry;
/** @var CategoryFactory $categoryFactory */
protected $categoryFactory
/**
* Category Deletion constructor.
* @param CategoryFactory $categoryFactory Category Factory
* @param Registry $registry Magento Registry
*/
public function __construct(
CategoryFactory $categoryFactory,
Registry $registry
) {
$this->categoryFactory = $categoryFactory;
$this->registry = $registry;
}
/**
* Remove categories tree
*
* @return void
*/
protected function removeCategories()
{
$categories = $this->categoryFactory->create()->getCollection();
$this->registry->register("isSecureArea", true);
foreach($categories 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
The code above only works if you have injected registry and get object manager singleton. This code shows how this can be done:
class MyClass{
protected $_objectManager;
protected $_registry;
...
public function __construct(
\Magento\Framework\Registry $registry,
...
) {
...
$this->_registry = $registry;
$this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
}
May this will helps you!