Magento 2 How to Disable Empty Category Programmatically Using Root Script?
In Magento 2, sometimes you may want to automatically disable categories that do not contain any products. This tutorial explains how to disable empty categories programmatically using a root PHP script in Magento 2.
Before Running the Script - Category Status
Step 1: Create Root Script File
Create a new PHP file inside your Magento root directory using the following path:
magento_root_directory/Categoryrootscript.php
<?php
use Magento\Framework\AppInterface;
try
{
require_once __DIR__ . '/app/bootstrap.php';
}
catch (\Exception $e)
{
echo 'Autoload error: ' . $e->getMessage();
exit(1);
}
try
{
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
$Collectionfactory = $objectManager->get(
'\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory'
);
$Categoryfactory = $objectManager->get(
'\Magento\Catalog\Model\CategoryFactory'
);
$Disablecategory = false;
$categories = $Collectionfactory->create()
->addAttributeToSelect('*');
foreach ($categories as $category)
{
$products = $category->getProductsPosition();
if (empty($products))
{
$category = $Categoryfactory->create()
->setStoreId(0)
->load($category->getId());
$category->setIsActive(0);
$category->save();
$Disablecategory = true;
}
}
if ($Disablecategory)
{
echo "Category disable successfully Done...";
}
else
{
echo "Category disable failed!";
}
}
catch(\Exception $e)
{
echo "Error : " . $e->getMessage();
}
?>
Step 2: Run the Script
After creating the file successfully, run the script directly in your browser using the URL below:
https://yourdomain.com/Categoryrootscript.php
After Running the Script - Category Status
Conclusion
Using this Magento 2 root script, you can quickly disable empty categories programmatically and keep your catalog clean and organized. This method is useful for large Magento stores where manually checking categories takes too much time.