Hiding Empty Categories in Magento: A Comprehensive Guide
As a developer working with Magento, you might often face situations where you need to hide empty categories and sub-categories from the frontend. Manually managing this through the admin panel can be time-consuming and inefficient when dealing with large product catalogs. In this blog post, we’ll explore an effective solution to automatically hide categories without any products.
Understanding the Problem
The current approaches suggested by Magento Stack Exchange and Josh Prattski’s blog provide modules for hiding empty categories. However, these solutions might not work correctly due to updates in later versions of Magento or specific customizations made to your store.
To resolve this issue accurately, let’s dive into a step-by-step approach that ensures the proper functioning of the category hide feature:
Step 1: Create a Custom Module
Firstly, you need to create a custom module within your Magento installation. This module will contain the logic for hiding empty categories.
Navigate to the app/code directory in your Magento root folder and create a new subdirectory following the namespace and module structure (e.g., Magento/EmptyCategories). Inside this directory, create the necessary files:
- app/code/Magento/EmptyCategories
- etc
- config.xml
- Model
- Config.php
Step 2: Define Configuration
Create a config.xml file inside the etc folder to define your module configuration:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magento_EmptyCategories" setup_version="1.0.0">
<sequence>
<module name="Magento_Catalog"/>
</sequence>
</module>
</config>
This configuration ensures that your module loads before the Magento_Catalog module, allowing you to modify category behavior.
Step 3: Create a Custom Category Model
Inside the Model folder, create a Config.php file:
<?php
namespace Magento\EmptyCategories\Model;
class Config extends \Magento\Framework\App\Config\ScopeConfigInterface
{
const XML_PATH_HIDE_EMPTY_CATEGORIES = 'catalog/category/hide_empty';
public function getHideEmptyCategories()
{
return $this->getValue(self::XML_PATH_HIDE_EMPTY_CATEGORIES);
}
}
This model extends the Magento\Framework\App\Config\ScopeConfigInterface and defines a configuration path (catalog/category/hide_empty) to enable or disable the empty category hiding feature.
Step 4: Hide Empty Categories
To hide empty categories, you need to modify the category collection query. Create a new observer:
- app/code/Magento/EmptyCategories/etc
- events.xml
In events.xml, define an observer for the catalog_category_collection_load_before event:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:event/etc/events.xsd">
<event name="catalog_category_collection_load_before">
<observer name="hide_empty_categories" instance="Magento\EmptyCategories\Observer\HideEmptyCategories" />
</event>
</config>
Now, create the HideEmptyCategories.php observer:
- app/code/Magento/EmptyCategories/Observer
class HideEmptyCategories implements \Magento\Framework\Event\ObserverInterface
{
protected $_categoryCollectionFactory;
protected $_categoryFactory;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
\Magento\Catalog\Model\CategoryFactory $categoryFactory
) {
$this->_categoryCollectionFactory = $categoryCollectionFactory;
$this->_categoryFactory = $categoryFactory;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
if ($observer->getCategoryCollection()->isLoaded()) {
$collection = $observer->getCategoryCollection();
$hideEmptyCategories = (bool)$this->_config->getHideEmptyCategories();
foreach ($collection as $category) {
$_productCollection = $this->_categoryFactory->create()
->getProductCollection()
->addAttributeToFilter('category_id', array('eq' => $category->getId()), 'left')
->addFieldToSelect(array('entity_id'));
if (count($_productCollection) == 0 && $hideEmptyCategories) {
$collection->removeItemByKey($category->getId());
}
}
}
return $this;
}
}
This observer checks for the catalog_category_collection_load_before event and filters out empty categories based on the configured setting.
Step 5: Enable Your Custom Module
To enable your custom module, navigate to the Magento admin panel:
- Log in as an administrator.
- Go to “Stores” > “Configuration” > “Advanced”.
- Click on the “Enable Modules Output” link.
- Search for and select your newly created
Magento_EmptyCategoriesmodule.
Step 6: Configure Empty Category Hiding
Finally, configure the empty category hiding option:
- In the Magento admin panel, navigate to “Stores” > “Configuration” > “Catalog”.
- Click on the “Category Options” link.
- Find the “Hide Empty Categories” setting under the “General Options” section.
- Enable or disable this setting based on your requirements.
Conclusion
Automatically hiding empty categories in Magento is a crucial task for maintaining a clean and organized product catalog. By following this comprehensive guide, you can now efficiently manage category visibility without manual intervention.
Remember to always test your customizations thoroughly after implementation, as they might affect other parts of your store’s functionality.
For more information on Magento development best practices and advanced features, visit our website at https://laravelcompany.com.