How to Sort Magento 2 Category Products by Stock Quantity
A visitor lands to your category page, scroll downs, see out of stock products first, gets disappointed and leaves the site. He left the store with a bad impression by seeing more out of stock products first and thus he even didn’t bother to scroll but leave.
For Magento 2 store owners, it is important to design the frontend of the store keeping the product stock in mind. The products having more quantity must be featured or displayed in the first fold rather than out of stock products. If a customer orders an out of stock product, his order processing takes time and hence it may deteriorate the customer experience and creates a first bad impression.
in Magento 2, if the user applies the sort options on product category such as products according to price, position or ratings, the default Magento 2 will display the products as per the filter applied. As users can’t apply two sorting options at a time, they will get results mixed with in-stock and out of stock products.
If you, as a Magento 2 store owner, want to combine the filter results of the users with stock quantity, you need to customize the functionality as default Magento 2 does not facilitate it. you have to custom code to sort Magento 2 category products by stock quantity.
I have given a stepwise solution to apply two sorting options at a time, one which is selected by the user and the other is the stock quantity based sorting auto applied programmatically.
Steps to Sort Magento 2 Category Products by Stock Quantity:
Step 1: Create registration.php at path app/code/Meetanshi/StockQuantity/registration.php
1 2 3 4 5 6 |
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Meetanshi_StockQuantity', __DIR__ ); |
Step 2: Create module.xml at path app/code/Meetanshi/StockQuantity/etc/module.xml
1 2 3 4 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Meetanshi_StockQuantity" setup_version="1.0.0"/> </config> |
Step 3 Create events.xml at path app/code/Meetanshi/StockQuantity/etc/events.xml
1 2 3 4 5 6 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="catalog_block_product_list_collection"> <observer name="stockLast" instance="Meetanshi\StockQuantity\Observer\StockLast" /> </event> </config> |
Step 4: Create StockLast.php at path app/code/Meetanshi/StockQuantity/Observer/StockLast.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<?php namespace Meetanshi\StockQuantity\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\Event\Observer; use Magento\Catalog\Block\Product\ProductList\Toolbar as CoreToolbar; class StockLast implements ObserverInterface { protected $scopeConfig; protected $_storeManager; protected $coreToolbar; public function __construct( ScopeConfigInterface $scopeConfig, StoreManagerInterface $storeManager, CoreToolbar $toolbar ) { $this->scopeConfig = $scopeConfig; $this->_storeManager = $storeManager; $this->coreToolbar = $toolbar; } public function execute(Observer $observer) { $collection = $observer->getEvent()->getData('collection'); try { $websiteId = 0; $stockId = 'stock_id'; $collection->getSelect()->joinLeft( array('_inv' => $collection->getResource()->getTable('cataloginventory_stock_status')), "_inv.product_id = e.entity_id and _inv.website_id=$websiteId", array('stock_status') ); $collection->addExpressionAttributeToSelect('in_stock', 'IFNULL(_inv.stock_status,0)', array()); $collection->getSelect()->reset('order'); $collection->getSelect()->order('in_stock DESC'); //code for Filter Price Low to High or High to Low with stock filter. if ($this->coreToolbar->getCurrentOrder() == 'price') { $direction = $this->coreToolbar->getCurrentDirection(); $collection->getSelect()->order("min_price $direction"); } } catch (\Exception $e) { } return $this; } } |
Hopefully, the post may have helped you sort Magento 2 category products by stock quantity, keeping the user experience at first place!
I’d be pleased to solve any doubts regarding the topic. Please mention them in the comments section below.
Rate the post with 5 stars if you liked it.
Happy Coding!
Thank You 🙂
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
28 Comments
Do you have a solution for Magento 2.4? Thanks in advance!
Hello Matheus,
The above solution is not compatible with Magento 2.4
We will post the solution in future.
Do subscribe to get notified for the same.
Thank You
Hello Sanjay,
Do you have a solution that is compatible with the 2.4.6 Magento version?
Thanks in advance!!
Hey,
Once we get compatible with 2.4.6 after that we will update our blog and inform you for the same.
Not working with 2.3.2, my website_ id is 1 checked in the database.
My Products not coming stock-wise.
Hello Shan Haider,
The above code is working up to Magento version 2.3.3.
Debug the issue by adding the log of collection.
Thank You.
It´s not working for Magento 2.4. Any advice?
I created, no errors… nothing happened
Hello Frank,
The above solution is not compatible with Magento 2.4
We will post the solution in future.
Do subscribe to get notified for the same.
Thank you.
Hello, is there already an ordering update for version 2.4?
Hello,
The above solution is not compatible with Magento 2.4
I will post the solution in the future.
Do subscribe to Meetanshi’s blog posts to get notified for the same.
Thank you.
Hi ,
When i run this command setup:upgrade then this error is showing. How to i can fix this issue. Please check attached screenshot.
https://imgur.com/55idkO7
Thanks
Hello,
Please copy the code of the events.xml file again and use it.
Thank you.
I run a command di:compile getting an Error
Parse error: syntax error, unexpected ‘ ‘ (T_STRING), expecting function (T_FUNCTION) in /home/tonevint/public_html/app/code/Meetanshi/StockQuantity/Observer/StockLast.php on line 10
Screenshot : https://prnt.sc/vzmq5o
Hello Naeem,
In step 4: Create StockLast.php at path app/code/Meetanshi/StockQuantity/Observer/StockLast.php, you may have made a mistake while copying the file. Please do adjust the space. For me, it’s working properly with no error.
Thank you.
Hi, this solution is not sorting products by stock quantity. It is checking only “in_stock”. I need to show items with greater quantity at first and the items with smaller quantity after that. Here is this happening but this code is in M1. Can you make one like this
https://magento.stackexchange.com/a/44639/67038
Thanks
Hello Syed,
With this solution, the out of stock product will be displayed at last
To do it quantity wise, you need to set conditions accordingly.
Thanks.
Thanks for you solution. This is working in Magento 2.3.2-p2 with Search Engine MySql. But, If we configure the Elasticsearch 6+ that code is not working. Please check the code with Magento 2.3.2-p2 with Elasticsearch6+ .
Hello Ramanathan,
Welcome 🙂
I’ll just check and post the update.
Thank you.
hello
is it possible to do the following action with your module.
Frit red products with a stock higher than 2000?
Hello,
You need to add conditions as per your requirement.
Thanks.
sudo php bin/magento setup:upgrade
PHP Parse error: syntax error, unexpected ‘ ‘ (T_STRING), expecting ‘,’ or ‘)’ in /var/www/html/magento2/app/code/Meetanshi/StockQuantity/registration.php on line 3
fixed above error goy
t new on di:compile please advice
/var/www/html/magento2$ sudo php bin/magento setup:di:compile
Compilation was started.
Repositories code generation… 1/7 [====>———————–] 14% < 1 sec 60.0 MiBPHP Parse error: syntax error, unexpected ' ' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in /var/www/html/magento2/app/code/Meetanshi/StockQuantity/Observer/StockLast.php on line 10
Hey,
It seems there’s been a mistake in copying the code.
Please try again.
Thank you.
Worked like a charm for magento 2.3
Many thanks
Hey, thank you so much for the kind words 🙂
Not working with 2.3.1, can you please update it
The solution works fine with Magento 2.3.1
Please check if you have used the proper website id. We have used the static one and maybe that is causing the issue for you.
Dear sir Thank you