1

I want to products on product list will always be sorted from salable to not salable. Products which have "Add to cart" button should be show firstly(It should work for simple and configurable products)

I tried created plugin as is written in [https://magento.stackexchange.com/questions/178061/magento2-sort-products-and-search-result-by-stock-availability][1] :

//di.xml

    <type name="Magento\Catalog\Model\Layer">
            <plugin name="product_sort_by_stock" type="Company\Module\Model\Plugin\Layer"/>
    </type>

//app/code/Company/Module/Model/Plugin/Layer.php

    <?php declare(strict_types=1);
    
    namespace Company\Module\Model\Plugin;
    
    class Layer
    {
    
        public function aroundgetProductCollection(\Magento\Catalog\Model\Layer $subject, \Closure $proceed)
        {
            $selectedDirection = 'DESC';
            $collection = $proceed();
            $collection->getSelect()->order('is_salable '. $selectedDirection);
            return $collection;
        }
    }

But it not works for me. Products are not sorted in a correct order.

Could you advice me how to sort product collection by is_salable attribute? I have Magento 2.4.0 and Elasticsearch 7.9.2. I use multi source inventory. [1]: Magento2 sort products and search result by stock availability

2
  • Did you manage to find a way to do this? I am in a similar situation and see that I have to add is_salable attribute to the elastic search bucket list before searching / sorting ? It seems that stock_status is general and not per store view in the bucket
    – gabtzi
    Commented Feb 22, 2021 at 6:34
  • I have the same issue. Please let me know if you get a solution. Commented Jul 23, 2021 at 22:32

1 Answer 1

0
$collection->getSelect()->joinLeft(
         ['_inventory_table' => 'cataloginventory_stock_item'], 
         "_inventory_table.product_id = e.entity_id", ['is_in_stock']
  );
  $collection->getSelect()->order(['is_in_stock desc']);

Refernce: Magento2 Display out of stock products at last

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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