I am trying to add new custom sort by option on categories products listing page along with other existing options like Name , Position and Price.
To test my functionality i am directory doing changes to Magento core files Just for testing purpose , so that once it will work , i will create a separate custom module for that.
I have modified
vendor/magento/module-catalog/Block/Product/ListProduct.php
and i have added
$collection->getSelect()->joinLeft(
array("test" => 'sales_order_item'),
'main_table.entity_id = test.product_id',
array('qty_ordered'=>'SUM(test.qty_ordered)'))
->group('main_table.entity_id')
->order('qty_ordered ASC');
Just after this line.
$collection = $this->_getProductCollection();
In below function
protected function _beforeToHtml()
But i am getting error as
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'main_table.entity_id' in 'on clause'
Can anybody please help , where i am wrong and is there any better method to complimenting sort by best sellers option in Magento 2.
Thanks
Best Answer
Here is an easy clean way to achieve this without overriding Magento core. Create NameSpace\ModuleName\etc\frontend\di.xml file with current configuration:
Then create plugin class NameSpace\ModuleName\Plugin\Catalog\Product\Sorting\Bestsellers.php:
And enjoy =)