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();
            }
        }

    }

}

1 Comment

Aref · January 11, 2018 at 10:23 am

I’m getting
Fatal error: Uncaught TypeError: Argument 1 passed to CategoryDeletion::__construct() must be an instance of Magento\Catalog\Model\CategoryFactory, none given,

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.