How To

How to Add Stock Filter on Category Layered Navigation in Magento 2?

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

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!

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 added the files but I don't see any changes. Question: shouldn't there bea registration.php and a module.xml file?
    Thank you

  • 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?

    • You need to apply the solution into third party extension and that extension must be enabled.

    • Magento Older version may need some code level changes according to the structure. Still you can try the same first into that one.

Recent Posts

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

1 day ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

2 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

4 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

6 days ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

7 days ago

Best Beginners Guide to Shopify Balance Account

If you are a Shopify admin, using a Shopify Balance Account for your business revenue…

7 days ago