[Magento 2] Delete All Categories Programmatically

There are a lot of articles on Internet proposing the deletion of all categories using a sql query. I’ve tested one of them and I’ve run into several problems due to this (url keys not deleted correctly, deletion of the Default category…). There is a safer way, using Magento tools. Things you need to know:

  • You’ll need to inject the classes CategoryFactory and Registry
  • Before deleting a category, it’s necessary to use the Registry to set a securedArea (adminhtml)
  • URL keys and other references are removed, and thus you won’t find any issues related to that in the future
  • We remove categories with ID > 2 to avoid the deletion of the default category
<?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();
            }
        }

    }

}

Leave a Reply

Your email address will not be published.