cancel
Showing results for 
Search instead for 
Did you mean: 

Out of stock products at the end of the category page - Magento 2.2.x

Out of stock products at the end of the category page - Magento 2.2.x

Out of stock products at the end of the category page - Magento 2.2.x

I am running Magento 2.2.4 version and I need to display Out of stock products at the end of the categories page.

 

I have added the below code in vendor/magento/module-catalog/Block/Product/layer.php 

 

$collection->joinField('in_stock', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id', 'in_stock>=0', 'left')->setOrder('in_stock','desc');

 

But its not working

 

Can anyone let me know how to display out of stock products at the end of the page?

 

Thanks.  

1 REPLY

Re: Out of stock products at the end of the category page - Magento 2.2.x

To do this you should extend Toolbar Block because that is an entry point which set order for layer

1) Add plugin to frontend DI:

    <type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
        <plugin name="add_collection_order_in_toolbar" type="Acme\InStockOrder\Model\ToolbarCollectionOrder"/>
    </type>

2) Add Plugin functionality (afterSetCollection method):

if (!$collection->getFlag('stock_order_applied')) {
    // Dump origin order part
    $order = $collection->getSelect()->getPart(Select::ORDER);

    // Add custom order
    $collection->joinField(
        'acme_stock_status',
        'cataloginventory_stock_status',
        'stock_status',
        'product_id=entity_id',
        null,
        'left'
    );
    $collection->addAttributeToSort('acme_stock_status', 'DESC');

    // Dump new order part & push custom order to first position
    $new = $collection->getSelect()->getPart(Select::ORDER);
    $reversed = array_reverse($new);
    $last = array_shift($reversed);
    $order = array_merge([$last], $order);

    // Release dump
    $collection->getSelect()->setPart(Select::ORDER, $order);
    $collection->setFlag('stock_order_applied', true);
}

Reverse ORDER part of Select needs because your custom order condition should be first to sort as you need and apply default sorting.


If you will have some difficulties you can install this example module link (30days only)