I want to move out of stock product in last of the category listing, itried below code but same seems not working.
app/code/Meetanshi/StockQuantity/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Meetanshi_StockQuantity" setup_version="1.0.0"/>
</config>
app/code/Meetanshi/StockQuantity/etc/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="catalog_block_product_list_collection">
<observer name="stockLast" instance="Meetanshi\StockQuantity\Observer\StockLast" />
</event>
</config>
app/code/Meetanshi/StockQuantity/Observer/StockLast.php
<?php
namespace Meetanshi\StockQuantity\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Event\Observer;
use Magento\Catalog\Block\Product\ProductList\Toolbar as CoreToolbar;
class StockLast implements ObserverInterface
{
protected $scopeConfig;
protected $_storeManager;
protected $coreToolbar;
public function __construct(
ScopeConfigInterface $scopeConfig,
StoreManagerInterface $storeManager,
CoreToolbar $toolbar
)
{
$this->scopeConfig = $scopeConfig;
$this->_storeManager = $storeManager;
$this->coreToolbar = $toolbar;
}
public function execute(Observer $observer)
{
$collection = $observer->getEvent()->getData('collection');
try {
$websiteId = 0;
$stockId = 'stock_id';
$collection->getSelect()->joinLeft(
array('_inv' => $collection->getResource()->getTable('cataloginventory_stock_status')),
"_inv.product_id = e.entity_id and _inv.website_id=$websiteId",
array('stock_status')
);
$collection->addExpressionAttributeToSelect('in_stock', 'IFNULL(_inv.stock_status,0)', array());
$collection->getSelect()->reset('order');
$collection->getSelect()->order('in_stock DESC');
//code for Filter Price Low to High or High to Low with stock filter.
if ($this->coreToolbar->getCurrentOrder() == 'price') {
$direction = $this->coreToolbar->getCurrentDirection();
$collection->getSelect()->order("min_price $direction");
}
} catch (\Exception $e) {
}
return $this;
}
}