Magento: Ensuring Out-of-Stock Products Appear Last on Category Pages
Out-of-stock products can clutter your category pages and confuse customers. In this post, we’ll explore how to ensure that out-of-stock items always appear last, even when sorting by price in Magento 1.7.0.2.
The Current Issue: Out-of-Stock Products Aren’t Always Last When Sorting by Price
You’ve already modified the /app/code/core/Mage/Catalog/Block/Product/list.php file to sort products by inventory status:
$this->productCollection = $layer->getProductCollection()
->joinField(
'inventory_in_stock',
'cataloginventory_stock_item',
'is_in_stock',
'product_id=entity_id',
'is_in_stock>0',
'left'
)->setOrder('inventory_in_stock','desc');
This code works perfectly for sorting by position or name. However, when sorting by price, the out-of-stock products don’t appear at the end of the list. This inconsistency can lead to a poor user experience.
The Solution: Modify the Join and Sort Conditions
To resolve this issue, we need to modify the join condition and sort order in your code:
$this->productCollection = $layer->getProductCollection()
->joinField(
'inventory_in_stock',
'cataloginventory_stock_item',
'is_in_stock',
'product_id=entity_id',
'is_in_stock<=0', // Change this line
'left'
)->setOrder(array('inventory_in_stock' => 'desc', 'price' => 'asc')); // Add price sorting here
Let’s break down the changes:
-
Modified Join Condition: We changed
is_in_stock>0tois_in_stock<=0. This ensures that only out-of-stock items (where stock is 0 or less) are included in the list. -
Added Price Sorting: We added a second sorting condition:
'price' => 'asc'. This tells Magento to sort products by price in ascending order (from lowest to highest). -
Array of Sort Conditions: We wrapped both conditions in an array. This allows multiple sorting criteria to be applied simultaneously.
How This Works
By joining only out-of-stock items and adding a sort condition for price, we ensure that:
- All out-of-stock products appear at the end of the list when sorted by any attribute.
- The remaining products are then sorted by their specified attribute (in your case, price).
This approach maintains consistency in how your category pages display products.
Conclusion
Ensuring a consistent user experience is crucial for driving sales and maintaining customer trust. By following this solution, you can guarantee that out-of-stock products always appear at the end of your Magento category pages, regardless of the sorting criteria used.
Remember to apply these changes carefully in a development environment first before moving them to production. For more advanced customizations and support, consider reaching out to Laravel Company.
Happy coding!