Hello Magento Friends,
Magento 2 offers a robust backend for product category management, but there are instances where you need to delete categories programmatically from a root script. This is especially helpful in the case of bulk category deletions, migration cleanup, or automation.

Here in this blog, I will describe how to delete categories from a root script in Magento 2 using category IDs.
Steps to Delete Categories using Root Script by Category IDs in Magento 2:
Step 1: Create a file in your Magento root directory at the following path
magento_root_directory\deletecategory.php
Then insert the code as follows
<?php
use Magento\Framework\App\Bootstrap;
use Magento\Framework\App\State;
use Magento\Framework\Registry;
use Magento\Catalog\Model\CategoryFactory;
require __DIR__ . '/../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
try {
// Set the area code to 'adminhtml'
$state = $objectManager->get(State::class);
try {
$state->setAreaCode('adminhtml');
} catch (\Magento\Framework\Exception\LocalizedException $e) {
// Area code already set, continue
}
// Define the category IDs to delete
$categoryIds = [3,4,5]; // Replace with your actual category IDs
// Load Registry
$registry = $objectManager->get(Registry::class);
foreach ($categoryIds as $categoryId) {
try {
// Load and delete the category
$categoryFactory = $objectManager->get(CategoryFactory::class);
$category = $categoryFactory->create()->load($categoryId);
if ($category->getId()) {
// Allow delete operation in non-secure area
$registry->register('isSecureArea', true);
$category->delete(); // Delete the category
// Unregister secure area
$registry->unregister('isSecureArea');
echo "This $categoryId Category ID is deleted successfully.";
} else {
echo "This $categoryId Category with ID Not deleted";
}
} catch (\Exception $e) {
echo "Something wrong went delete category: " . $e->getMessage();
}
}
} catch (\Exception $e) {
echo "Error: " . $e->getMessage();
}
Step 2: Now, after the above step, you must run the below-given URL.
https://yourdomain.com/deletecategory.php
Output:
Before Deleting Categories:

After Deleting Categories:

Conclusion:
With a basic root script, you can quickly remove several categories in Magento 2 by category IDs. This is time-saving and effort-saving, particularly when dealing with large catalogs.
In case you have some questions or need help, please leave a comment!

Happy Coding!