Mass delete magento 2 categories programmatically

This tutorial explains how to mass delete magento 2 categories programmatically. If you want to delete all the categories of magento 2 programmatically use the following script.Please also refer the tutorial which explains how to import magento 2 categories programmatically.

The following tutorial gives the step by step explanation of how to create the file, connect to magento database externally and delete the categories programmatically.

mass delete magento 2 categories programmatically

Step by step explanation

  • Connect magento database
  • Mass delete magento 2 categories

Connect magento database

As the first step create the deletecategory.php file inside the script folder in the magento root directory.

Mass delete magento 2 categories

The following code delete the magento categories programmatically except the root category.

use Magento\Framework\App\Bootstrap;
$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = Magento\Framework\App\ObjectManager::getInstance();

function deleteAllCategories($objectManager) {
    $categoryFactory = $objectManager->get('Magento\Catalog\Model\CategoryFactory');
    $newCategory = $categoryFactory->create();
    $collection = $newCategory->getCollection();
    $objectManager->get('Magento\Framework\Registry')->register('isSecureArea', true);

    foreach($collection as $category) {
        $category_id = $category->getId();
        if( $category_id <= 2 ) continue;
        try {
            echo 'Category Removed '.$category_id .PHP_EOL;
        } catch (Exception $e) {
            echo 'Failed to remove category '.$category_id .PHP_EOL;
            echo $e->getMessage() . "\n" .PHP_EOL;

Share this Tutorial

Leave a Reply

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