In an e-commerce store, it's essential to manage and display products based on their availability.

By default, Magento 2 displays out-of-stock products alongside in-stock products, which can confuse customers.

However, with the Magento 2.4.3-p1 update, it has become easier to prioritize and display out-of-stock products at the end of the page in the list.phtml template.

Method 1: Using addAttributeToSort()

One way to achieve this is by adding a custom attribute to sort the products. Open the list.phtml file located at MAGENTO\app\design\frontend\BASE\THEME\Magento_Catalog\templates\product\list.phtml and find the product collection query. Then, add the following line of code before the query


$collection->addAttributeToSort('is_in_stock', 'DESC');

This code will sort the products based on their stock status, displaying the out-of-stock products at the end of the page.

Method 2: Using order()

Alternatively, you can use the order() method to order the products. Locate the product collection query in the list.phtml file and modify it as follows


$collection->order('is_in_stock DESC');

This code will order the products in descending order based on their stock status, placing the out-of-stock products at the bottom.

Conclusion

Effectively managing and displaying out-of-stock products in an online store is crucial for a seamless shopping experience.

With the Magento 2.4.3-p1 update, you can easily prioritize and showcase out-of-stock items at the end of the page by using either the addAttributeToSort() or order() method in the list.phtml template.