2

I want to display out of stock products at the end of the category page of Magento 2.5.
I add this code:

vendor/magento/module-catalog/Block/Product/ListProduct.php

$collection = $layer->getProductCollection(); 

$this->_productCollection->getSelect()->order('is_salable DESC');

But shows error:

Fatal error: Uncaught Error: Call to a member function getSelect() on null

  • You mean to say you want to show all out of stock product at end of the list page? – Ravi Soni Jun 21 at 10:07
  • $collection->getSelect()->order('is_salable DESC'); add after second line – Ketan Borada Jun 21 at 10:54
  • Have you try below solution? – Chirag Patel Jun 21 at 11:18
0

For Collection of product generate from Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection file. We need to create a plugin for load() function. we need to set our custom condition for out of stock product to beforeLoad() function.

Create a di.xml file,

app/code/Namespace/OutOfStock/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <!--  out of stock product at end of list -->
    <type name="Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection">
        <plugin name="Namespace_OutOfStock::OutofstockEnd" type="Namespace\OutOfStock\Plugin\Product\ProductList\Toolbar"/>
    </type>
</config>

Need to override Stock.php file from Magento\CatalogInventory\Helper\Stock class.

Create Toolbar.php file, File Path, app/code/Rbj/OutOfStock/Plugin/Product/ProductList/Toolbar.php

<?php    

namespace Namespace\OutOfStock\Plugin\Product\ProductList;

class Toolbar
{
    /**
     * @param \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $subject
     * @param bool $printQuery
     * @param bool $logQuery
     * @return array
     */
    public function beforeLoad(\Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $subject, $printQuery = false, $logQuery = false)
    {
        $orderBy = $subject->getSelect()->getPart(\Zend_Db_Select::ORDER);
        $outOfStockOrderBy = array('is_salable DESC');
        /* reset default product collection filter */
        $subject->getSelect()->reset(\Zend_Db_Select::ORDER);
        $subject->getSelect()->order($outOfStockOrderBy);

        return [$printQuery, $logQuery];
    }
}

Clear Cache and Check in front. All the Out of stock product will display at end of listing page.

Take reference from Master!!!

I hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.