I want to Implement a new ordering function to order products in product lists pages based on Qty (Stock). I tried but something goes wrong. Help me out.
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">
<type name="Magento\Catalog\Model\Layer">
<plugin name="product_sort_by_stock" type="Company\Module\Model\Plugin\Layer"/>
</type>
</config>
....\Plugin\Catalog\Block
class SortStock
{
const STOCK_SORT_BY = 'qty';
public function afterGetAttributeUsedForSortByArray(Config $subject, $result)
{
return array_merge($result, [self::STOCK_SORT_BY => __('Qty')]);
}
public function beforeSetCollection(Toolbar $subject, Collection $collection)
{
if ($subject->getCurrentOrder() === self::STOCK_SORT_BY) {
$collection->getSelect()->joinLeft(
array('_inv' => $collection->getResource()->getTable('cataloginventory_stock_status')),
"_inv.product_id = e.entity_id",
array('stock_status')
);
$collection->addExpressionAttributeToSelect('in_stock', 'IFNULL(_inv.stock_status,0)', array());
$collection->getSelect()->reset('order');
$collection->getSelect()->order('in_stock DESC');
}
}
}