I tried to do it via layer collection :

$collection->getSelect()->order('is_salable DESC');

It works for catalog, but does not sort the result in search .


I found the solution in this layer plugin:

public function afterGetProductCollection(
    \Magento\Catalog\Model\Layer $subject,
    $collection = $result;
    if(!$this->_added) {
        if($this->isCatalogSearchCollection() && $collection && $this->useSelect()) {

                ['stock_item_table' => $collection->getResource()->getTable('cataloginventory_stock_item')],
                "e.entity_id = stock_item_table.product_id",
            $collection->getSelect()->order('is_in_stock DESC');
            $orders = $collection->getSelect()->getPart(\Zend_Db_Select::ORDER);
            array_unshift($orders, array_pop($orders));
            $collection->getSelect()->setPart(\Zend_Db_Select::ORDER, $orders);
            $this->_added = true;
            $collection->getSelect()->order('is_salable DESC');
            $this->_added = true;
    $result = $collection;
    return $result;

And i also added a class variable that comes up as false when class init, then after order is has been placed to avoid circle select and order method call:

 protected $_added = false;

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.