Hello Magento Friends,
Today we will learn How to Add Stock Filter on Category Layered Navigation in Magento 2.
Providing a seamless and efficient shopping experience to customers is paramount. One way to achieve this is by enabling useful filters that help customers narrow down their product searches.
Check out
- How To Configure Layered Navigation In Magento 2
- How to Expand default Layered Navigation Category Filters in Magento 2
Adding a stock filter to the category layered navigation in Magento 2 can greatly enhance the user experience by allowing customers to filter products based on their availability. Providing such filtering options can contribute to a more streamlined and customer-friendly shopping experience on your Magento 2 e-commerce platform.
In this tutorial, we will guide you through the process of adding a stock filter to the category layered navigation in your Magento 2 store.
Steps to Add Stock Filter on Category Layered Navigation in Magento 2:
Step 1: First, we need to create a “di.xml” file inside the extension at the following path.
app\code\Vendor\Extension\etc\frontend
Then add the code as below
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd"> <type name="Magento\Catalog\Model\Layer\FilterList"> <plugin name="stock-filter-category-navigation" type="Vendor\Extension\Model\Plugin\FilterList" sortOrder="100" /> </type> </config>
Step 2: After that, we need to create a “Stock.php” file inside the extension at the following path.
app\code\Vendor\Extension\Model\Layer\Filter
Now add the code as mentioned below
<?php namespace Vendor\Extension\Model\Layer\Filter; class Stock extends \Magento\Catalog\Model\Layer\Filter\AbstractFilter { const IN_STOCK_COLLECTION_FLAG = 'stock_filter_applied'; protected $_activeFilter = false; protected $_requestVar = 'in-stock'; protected $_scopeConfig; public function __construct( \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Catalog\Model\Layer\Filter\ItemFactory $filterItemFactory, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Catalog\Model\Layer $layer, \Magento\Catalog\Model\Layer\Filter\Item\DataBuilder $itemDataBuilder, array $data = [] ) { $this->_scopeConfig = $scopeConfig; parent::__construct($filterItemFactory, $storeManager, $layer, $itemDataBuilder, $data); } public function apply(\Magento\Framework\App\RequestInterface $request) { $filter = $request->getParam($this->getRequestVar(), null); if (is_null($filter)) { return $this; } $this->_activeFilter = true; $filter = (int)(bool)$filter; $collection = $this->getLayer()->getProductCollection(); $collection->setFlag(self::IN_STOCK_COLLECTION_FLAG, true); $collection->getSelect()->where('stock_status_index.stock_status = ?', $filter); $this->getLayer()->getState()->addFilter( $this->_createItem($this->getLabel($filter), $filter) ); return $this; } public function getName() { return __("Stock"); } protected function _getItemsData() { if ($this->getLayer()->getProductCollection()->getFlag(self::IN_STOCK_COLLECTION_FLAG)) { return []; } $data = []; foreach ($this->getStatuses() as $status) { $data[] = [ 'label' => $this->getLabel($status), 'value' => $status, 'count' => $this->getProductsCount($status) ]; } return $data; } public function getStatuses() { return [ \Magento\CatalogInventory\Model\Stock::STOCK_IN_STOCK, \Magento\CatalogInventory\Model\Stock::STOCK_OUT_OF_STOCK ]; } public function getLabels() { return [ \Magento\CatalogInventory\Model\Stock::STOCK_IN_STOCK => __('In Stock'), \Magento\CatalogInventory\Model\Stock::STOCK_OUT_OF_STOCK => __('Out of stock'), ]; } public function getLabel($value) { $labels = $this->getLabels(); if (isset($labels[$value])) { return $labels[$value]; } return ''; } public function getProductsCount($value) { $collection = $this->getLayer()->getProductCollection(); $select = clone $collection->getSelect(); // reset columns, order and limitation conditions $select->reset(\Zend_Db_Select::COLUMNS); $select->reset(\Zend_Db_Select::ORDER); $select->reset(\Zend_Db_Select::LIMIT_COUNT); $select->reset(\Zend_Db_Select::LIMIT_OFFSET); $select->where('stock_status_index.stock_status = ?', $value); $select->columns( [ 'count' => new \Zend_Db_Expr("COUNT(e.entity_id)") ] ); return $collection->getConnection()->fetchOne($select); } }
Step 3: After that, we need to create the “FilterList.php” file inside the extension at the following path.
app\code\Vendor\Extension\Model\Plugin
And finally, add the code as follows
<?php namespace Vendor\Extension\Model\Plugin; class FilterList { const STOCK_FILTER_CLASS = 'Vendor\Extension\Model\Layer\Filter\Stock'; protected $_objectManager; protected $_layer; protected $_storeManager; protected $_stockResource; protected $_scopeConfig; public function __construct( \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\ObjectManagerInterface $objectManager, \Magento\CatalogInventory\Model\ResourceModel\Stock\Status $stockResource, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig ) { $this->_storeManager = $storeManager; $this->_objectManager = $objectManager; $this->_stockResource = $stockResource; $this->_scopeConfig = $scopeConfig; } public function isEnabled() { $outOfStockEnabled = $this->_scopeConfig->isSetFlag( \Magento\CatalogInventory\Model\Configuration::XML_PATH_DISPLAY_PRODUCT_STOCK_STATUS, \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); return $outOfStockEnabled; } public function beforeGetFilters( \Magento\Catalog\Model\Layer\FilterList\Interceptor $filterList, \Magento\Catalog\Model\Layer $layer ) { $this->_layer = $layer; if ($this->isEnabled()) { $collection = $layer->getProductCollection(); $websiteId = $this->_storeManager->getStore($collection->getStoreId())->getWebsiteId(); $this->_addStockStatusToSelect($collection->getSelect(), $websiteId); } return array($layer); } public function afterGetFilters( \Magento\Catalog\Model\Layer\FilterList\Interceptor $filterList, array $filters ) { if ($this->isEnabled()) { $filters[] = $this->getStockFilter(); } return $filters; } public function getStockFilter() { $filter = $this->_objectManager->create( $this->getStockFilterClass(), ['layer' => $this->_layer] ); return $filter; } public function getStockFilterClass() { return self::STOCK_FILTER_CLASS; } protected function _addStockStatusToSelect(\Zend_Db_Select $select, $websiteId) { $from = $select->getPart(\Zend_Db_Select::FROM); if (!isset($from['stock_status_index'])) { $joinCondition = $this->_stockResource->getConnection()->quoteInto( 'e.entity_id = stock_status_index.product_id' . ' AND stock_status_index.website_id = ?', $websiteId ); $joinCondition .= $this->_stockResource->getConnection()->quoteInto( ' AND stock_status_index.stock_id = ?', \Magento\CatalogInventory\Model\Stock::DEFAULT_STOCK_ID ); } return $this; } }
Step 4: Once all files are created in your Magento, you need to run Magento upgrade, compile and deploy commands as follows.
php bin/magento setup:upgrade php bin/magento setup:static-content:deploy -f php bin/magento setup:di:compile php bin/magento cache:clean php bin/magento cache:flush
Output:
Visit your Magento 2 store’s category page, and you should now see the stock filter in the layered navigation.
Now if the customer selects the In Stock option in the Stock filter menu, it will show the products that are available for purchase.
And if the customer selects the Out of Stock option, it will show the products that are currently not in stock.
Conclusion:
By following these steps, you can enhance the user experience of your Magento 2 store by adding a stock filter to the category layered navigation. This will enable customers to filter products based on their availability, helping them find products currently in or out of stock.
If you face any errors while adding a stock filter on category layered navigation, drop a comment here, and I will quickly provide you with the appropriate solution.
Share the tutorial to add stock filters in Magento 2 with your friends, and stay tuned for more such content.
Happy Coding!
Hi,
Is this compatible with v2.3?
Cannot get the attribute to show on frontend.
Magento Older version may need some code level changes according to the structure. Still you can try the same first into that one.
Do this require enabling?
Kindly assist.
You need to apply the solution into third party extension and that extension must be enabled.
Hi,
In Magento 2.4.6 the filter need to have an AttributeModel, how can i set an attributeModel for this since there’s no attribute for stock?
For the Magento Version change, you need to further customize the code according to requirements.
For more information you can contact on : support@magecomp.com
Hi,
I added the files but I don’t see any changes. Question: shouldn’t there bea registration.php and a module.xml file?
Thank you
Yes you need to create another required file for third party extension and confirm extension is enable.