Deleting all empty categories and sub-categories is not easy in magento 2. To delete empty categories in magento 2 you need to find each categories in backend and delete them one by one manually. In case there are lots of empty categories created with any import script and extension then it can become a cumbersome task.
However, using the following script it is very easy to delete empty categories programatically.
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('global');
$objectManager = Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->get('Magento\Catalog\Model\CategoryFactory');
$newCategory = $categoryFactory->create();
$collection = $newCategory->getCollection();
$registry = $objectManager->get('\Magento\Framework\Registry');
$registry->register("isSecureArea", true);
foreach($collection as $category) {
if($category->getId() > 2){
$category = $objectManager->create('Magento\Catalog\Model\Category')->load($category->getId());
if($category->getProductCollection()->count()==0){
$category->delete();
}
}
}
You need to put the above code in the a php file in the magento root and you can run it by browser with domainname/scriptname and it will remove all empty categories from the magento.
NOTE: It is always advised to create a backup of magento website before running such direct scripts.