How To

How to Disable Empty Category Programmatically using Root Script in Magento 2?

Hello Magento Friends,

The subject matter of today’s Magento technical solution is How to Disable Empty Category Programmatically using Root Script in Magento 2?

Categories in Magento 2 help to sort products. Categories help customers to find products easily. But if you have an empty category, it will show an empty page to the customer, which will affect the store’s customer experience. Hence, store owners must disable or delete empty categories from the storefront.

Categories can be disabled from the Magento 2 admin panel. Alternatively, you can disable categories programmatically also.

Let’s find out how to disable empty categories programmatically using the root script in Magento 2.

Steps to Disable Empty Category Programmatically using Root Script in Magento 2:

Category position before running the script

Step 1: Create a file in your Magento root directory at the below path. 

magento_root_directory\Disablecategory.php

Then add the code as below

<?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'); 
       $Categorydisable=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();
    $Categorydisable=true;
              }
       }
       if($Categorydisable)
       {
        echo "Category disable successfull";
       }
       else
       {
            echo "Category disable failed!";     
       }
}
catch(\Exception $e)
{
       echo "Error : ".$e->getMessage();
}
?>

Step 2: After the above step, you will need to run the below-given URL.

https://yourdomain.com/Disablecategory.php 

Category position after running the script

Conclusion:

Hopefully, you were able to disable the empty category programmatically in Magento 2. You can also change the position of the category programmatically in Magento 2.

Share the tutorial with your Magento friends and stay updated for more Magento tutorial guides.

Happy Coding!

Click to rate this post!
[Total: 1 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

  • Hi,

    I am looking to simply hide the categories that have been added and put on the frontend of my site, but not to completely remove them from the admin area - because if I add a product to that empty category, I want it to display and become "unhidden". Will the provided code above do this for me?

    • The above code is to disable the category, so once particular category is disabled, it will not show on Magento frontend.

Recent Posts

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

3 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

1 day ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

1 day ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago