Magento 2 add Sort By Best Sellers Option on category products litsing pageMagento 2 Sort by New Products and Most View ProductMagento 2 sort optionsMagento 2 : Sort By block is missing after override the toolbar for search page?Add new options into sorterHow to sort product by best seller Magento 2.1 without changing in core fileSort by Product OrderedHow add category programmatically magento 2Get random products from category in magento 2Magento 2: Custom Category pageWhy “Use Parent Category Path for Category URLs” option is not available in Magento 2?Not getting Customer details on Home Page, Category pageMagento 2.1.7 Import Products stuckList Products of CategoryHow to add Please Select option in programmatically created select attribute for products?Magento 2 - Add 'per page' text inside option tagRandomly sort products in catalog
Splitting fasta file into smaller files based on header pattern
Pre-Employment Background Check With Consent For Future Checks
Is there any common country to visit for uk and schengen visa?
Why doesn't the fusion process of the sun speed up?
Should I be concerned about student access to a test bank?
TDE Master Key Rotation
What kind of footwear is suitable for walking in micro gravity environment?
Friend wants my recommendation but I don't want to
Unfrosted light bulb
What is it called when someone votes for an option that's not their first choice?
How to remove space in section title at KOMA-Script
Would mining huge amounts of resources on the Moon change its orbit?
What are rules for concealing thieves tools (or items in general)?
Single word to change groups
Is xar preinstalled on macOS?
Writing in a Christian voice
Exposing a company lying about themselves in a tightly knit industry: Is my career at risk on the long run?
Error in master's thesis, I do not know what to do
How to test the sharpness of a knife?
Would storms on an ocean world harm the marine life?
How to read string as hex number in bash?
Someone scrambled my calling sign- who am I?
What will the french man say?
Does Shadow Sorcerer's Eyes of the Dark work on all magical darkness or just his/hers?
Magento 2 add Sort By Best Sellers Option on category products litsing page
Magento 2 Sort by New Products and Most View ProductMagento 2 sort optionsMagento 2 : Sort By block is missing after override the toolbar for search page?Add new options into sorterHow to sort product by best seller Magento 2.1 without changing in core fileSort by Product OrderedHow add category programmatically magento 2Get random products from category in magento 2Magento 2: Custom Category pageWhy “Use Parent Category Path for Category URLs” option is not available in Magento 2?Not getting Customer details on Home Page, Category pageMagento 2.1.7 Import Products stuckList Products of CategoryHow to add Please Select option in programmatically created select attribute for products?Magento 2 - Add 'per page' text inside option tagRandomly sort products in catalog
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
magento-2.0 magento-2.1
add a comment |
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
magento-2.0 magento-2.1
add a comment |
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
magento-2.0 magento-2.1
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
magento-2.0 magento-2.1
magento-2.0 magento-2.1
edited Sep 12 '16 at 10:33
Dinesh Saini
asked Sep 12 '16 at 10:20
Dinesh SainiDinesh Saini
385217
385217
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
Finally i have completed it like this , may be it will help someone else
First i have added these 2 lines in CompanyModuleetcfrontenddi.xml to update the core blocks
<preference for="MagentoCatalogBlockProductProductListToolbar" type="CompanyModuleBlockProductProductListToolbar"/>
<preference for="MagentoCatalogModelConfig" type="CompanyModuleModelConfig"/>
Then created Config Model
CompanyModuleModelConfig with below script
class Config extends MagentoCatalogModelConfig
public function getAttributeUsedForSortByArray()
$options = ['bestseller' => __('Best seller')];
foreach ($this->getAttributesUsedForSortBy() as $attribute)
/* @var $attribute MagentoEavModelEntityAttributeAbstractAttribute */
$options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
return $options;
The Created a block
CompanyModuleBlockProductProductListToolbar with below script
class Toolbar extends MagentoCatalogBlockProductProductListToolbar
public function setCollection($collection)
if($this->getCurrentOrder()=="bestseller")
$collection->getSelect()->joinLeft(
'sales_order_item',
'e.entity_id = sales_order_item.product_id',
array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)'))
->group('e.entity_id')
->order('qty_ordered '.$this->getCurrentDirectionReverse());
$this->_collection = $collection;
$this->_collection->setCurPage($this->getCurrentPage());
$limit = (int)$this->getLimit();
if ($limit)
$this->_collection->setPageSize($limit);
if ($this->getCurrentOrder())
$this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
return $this;
public function getCurrentDirectionReverse()
if ($this->getCurrentDirection() == 'asc')
return 'desc';
elseif ($this->getCurrentDirection() == 'desc')
return 'asc';
else
return $this->getCurrentDirection();
its works fine but, its removed position sort by option.
– Rajkumar .E
Apr 11 '17 at 13:34
You don't need to create config.php just create a new attribute and set yes for used in sorting at product listing. It will not remove position sort by option.
– Ramkishan Suthar
Oct 20 '17 at 15:06
@Dinesh Saini , I have overrided toolbar block like you said / suggested but sort by option is missing in search page . apart from this anything still missing?
– Pramod Kharade
Dec 7 '17 at 9:13
Hi, I am getting error "Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'qty_ordered ' in 'order clause'" while using this code. Please help with the solution.
– Udit Gupta
Jul 5 '18 at 9:19
add a comment |
Here is an easy clean way to achieve this without overriding Magento core.
Create NameSpaceModuleNameetcfrontenddi.xml file with current configuration:
<!-- Adding Sort by Bestsellers functionality -->
<type name="MagentoCatalogBlockProductProductListToolbar">
<plugin name="before_set_collection" type="NameSpaceModuleNamePluginCatalogProductSortingBestsellers" />
</type>
<type name="MagentoCatalogModelConfig">
<plugin name="after_get_available_orders" type="NameSpaceModuleNamePluginCatalogProductSortingBestsellers" />
</type>
Then create plugin class NameSpaceModuleNamePluginCatalogProductSortingBestsellers.php:
namespace NameSpaceModuleNamePluginCatalogProductSorting;
use MagentoCatalogBlockProductProductListToolbar;
use MagentoCatalogModelConfig;
use MagentoFrameworkDataCollection;
class Bestsellers
/**
* Bestsellers sorting attribute
*/
const BESTSELLERS_SORT_BY = 'bestsellers';
/**
* @param Config $subject
* @param $result
* @return array
*/
public function afterGetAttributeUsedForSortByArray(Config $subject, $result)
return array_merge($result, [self::BESTSELLERS_SORT_BY => __('Bestsellers')]);
/**
* @param Toolbar $subject
* @param Collection $collection
*/
public function beforeSetCollection(Toolbar $subject, Collection $collection)
if ($subject->getCurrentOrder() == self::BESTSELLERS_SORT_BY)
$collection->getSelect()->joinLeft(
'sales_order_item',
'e.entity_id = sales_order_item.product_id',
array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)'))
->group('e.entity_id')
->order('qty_ordered '.$subject->getCurrentDirection());
And enjoy =)
add a comment |
The drawback of using sales_order_item.qty_ordered is lifetime sales, i.e. products with high recent sales will be in bottom of page.
I suggest create new index table, with product_id, SUM(qty_ordered) during last 30 days and sort by these values. Plus add second sorting factor by adding date.
Similar solution was implemented in Intelligent Sorting Extension

add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f135871%2fmagento-2-add-sort-by-best-sellers-option-on-category-products-litsing-page%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Finally i have completed it like this , may be it will help someone else
First i have added these 2 lines in CompanyModuleetcfrontenddi.xml to update the core blocks
<preference for="MagentoCatalogBlockProductProductListToolbar" type="CompanyModuleBlockProductProductListToolbar"/>
<preference for="MagentoCatalogModelConfig" type="CompanyModuleModelConfig"/>
Then created Config Model
CompanyModuleModelConfig with below script
class Config extends MagentoCatalogModelConfig
public function getAttributeUsedForSortByArray()
$options = ['bestseller' => __('Best seller')];
foreach ($this->getAttributesUsedForSortBy() as $attribute)
/* @var $attribute MagentoEavModelEntityAttributeAbstractAttribute */
$options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
return $options;
The Created a block
CompanyModuleBlockProductProductListToolbar with below script
class Toolbar extends MagentoCatalogBlockProductProductListToolbar
public function setCollection($collection)
if($this->getCurrentOrder()=="bestseller")
$collection->getSelect()->joinLeft(
'sales_order_item',
'e.entity_id = sales_order_item.product_id',
array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)'))
->group('e.entity_id')
->order('qty_ordered '.$this->getCurrentDirectionReverse());
$this->_collection = $collection;
$this->_collection->setCurPage($this->getCurrentPage());
$limit = (int)$this->getLimit();
if ($limit)
$this->_collection->setPageSize($limit);
if ($this->getCurrentOrder())
$this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
return $this;
public function getCurrentDirectionReverse()
if ($this->getCurrentDirection() == 'asc')
return 'desc';
elseif ($this->getCurrentDirection() == 'desc')
return 'asc';
else
return $this->getCurrentDirection();
its works fine but, its removed position sort by option.
– Rajkumar .E
Apr 11 '17 at 13:34
You don't need to create config.php just create a new attribute and set yes for used in sorting at product listing. It will not remove position sort by option.
– Ramkishan Suthar
Oct 20 '17 at 15:06
@Dinesh Saini , I have overrided toolbar block like you said / suggested but sort by option is missing in search page . apart from this anything still missing?
– Pramod Kharade
Dec 7 '17 at 9:13
Hi, I am getting error "Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'qty_ordered ' in 'order clause'" while using this code. Please help with the solution.
– Udit Gupta
Jul 5 '18 at 9:19
add a comment |
Finally i have completed it like this , may be it will help someone else
First i have added these 2 lines in CompanyModuleetcfrontenddi.xml to update the core blocks
<preference for="MagentoCatalogBlockProductProductListToolbar" type="CompanyModuleBlockProductProductListToolbar"/>
<preference for="MagentoCatalogModelConfig" type="CompanyModuleModelConfig"/>
Then created Config Model
CompanyModuleModelConfig with below script
class Config extends MagentoCatalogModelConfig
public function getAttributeUsedForSortByArray()
$options = ['bestseller' => __('Best seller')];
foreach ($this->getAttributesUsedForSortBy() as $attribute)
/* @var $attribute MagentoEavModelEntityAttributeAbstractAttribute */
$options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
return $options;
The Created a block
CompanyModuleBlockProductProductListToolbar with below script
class Toolbar extends MagentoCatalogBlockProductProductListToolbar
public function setCollection($collection)
if($this->getCurrentOrder()=="bestseller")
$collection->getSelect()->joinLeft(
'sales_order_item',
'e.entity_id = sales_order_item.product_id',
array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)'))
->group('e.entity_id')
->order('qty_ordered '.$this->getCurrentDirectionReverse());
$this->_collection = $collection;
$this->_collection->setCurPage($this->getCurrentPage());
$limit = (int)$this->getLimit();
if ($limit)
$this->_collection->setPageSize($limit);
if ($this->getCurrentOrder())
$this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
return $this;
public function getCurrentDirectionReverse()
if ($this->getCurrentDirection() == 'asc')
return 'desc';
elseif ($this->getCurrentDirection() == 'desc')
return 'asc';
else
return $this->getCurrentDirection();
its works fine but, its removed position sort by option.
– Rajkumar .E
Apr 11 '17 at 13:34
You don't need to create config.php just create a new attribute and set yes for used in sorting at product listing. It will not remove position sort by option.
– Ramkishan Suthar
Oct 20 '17 at 15:06
@Dinesh Saini , I have overrided toolbar block like you said / suggested but sort by option is missing in search page . apart from this anything still missing?
– Pramod Kharade
Dec 7 '17 at 9:13
Hi, I am getting error "Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'qty_ordered ' in 'order clause'" while using this code. Please help with the solution.
– Udit Gupta
Jul 5 '18 at 9:19
add a comment |
Finally i have completed it like this , may be it will help someone else
First i have added these 2 lines in CompanyModuleetcfrontenddi.xml to update the core blocks
<preference for="MagentoCatalogBlockProductProductListToolbar" type="CompanyModuleBlockProductProductListToolbar"/>
<preference for="MagentoCatalogModelConfig" type="CompanyModuleModelConfig"/>
Then created Config Model
CompanyModuleModelConfig with below script
class Config extends MagentoCatalogModelConfig
public function getAttributeUsedForSortByArray()
$options = ['bestseller' => __('Best seller')];
foreach ($this->getAttributesUsedForSortBy() as $attribute)
/* @var $attribute MagentoEavModelEntityAttributeAbstractAttribute */
$options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
return $options;
The Created a block
CompanyModuleBlockProductProductListToolbar with below script
class Toolbar extends MagentoCatalogBlockProductProductListToolbar
public function setCollection($collection)
if($this->getCurrentOrder()=="bestseller")
$collection->getSelect()->joinLeft(
'sales_order_item',
'e.entity_id = sales_order_item.product_id',
array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)'))
->group('e.entity_id')
->order('qty_ordered '.$this->getCurrentDirectionReverse());
$this->_collection = $collection;
$this->_collection->setCurPage($this->getCurrentPage());
$limit = (int)$this->getLimit();
if ($limit)
$this->_collection->setPageSize($limit);
if ($this->getCurrentOrder())
$this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
return $this;
public function getCurrentDirectionReverse()
if ($this->getCurrentDirection() == 'asc')
return 'desc';
elseif ($this->getCurrentDirection() == 'desc')
return 'asc';
else
return $this->getCurrentDirection();
Finally i have completed it like this , may be it will help someone else
First i have added these 2 lines in CompanyModuleetcfrontenddi.xml to update the core blocks
<preference for="MagentoCatalogBlockProductProductListToolbar" type="CompanyModuleBlockProductProductListToolbar"/>
<preference for="MagentoCatalogModelConfig" type="CompanyModuleModelConfig"/>
Then created Config Model
CompanyModuleModelConfig with below script
class Config extends MagentoCatalogModelConfig
public function getAttributeUsedForSortByArray()
$options = ['bestseller' => __('Best seller')];
foreach ($this->getAttributesUsedForSortBy() as $attribute)
/* @var $attribute MagentoEavModelEntityAttributeAbstractAttribute */
$options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
return $options;
The Created a block
CompanyModuleBlockProductProductListToolbar with below script
class Toolbar extends MagentoCatalogBlockProductProductListToolbar
public function setCollection($collection)
if($this->getCurrentOrder()=="bestseller")
$collection->getSelect()->joinLeft(
'sales_order_item',
'e.entity_id = sales_order_item.product_id',
array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)'))
->group('e.entity_id')
->order('qty_ordered '.$this->getCurrentDirectionReverse());
$this->_collection = $collection;
$this->_collection->setCurPage($this->getCurrentPage());
$limit = (int)$this->getLimit();
if ($limit)
$this->_collection->setPageSize($limit);
if ($this->getCurrentOrder())
$this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
return $this;
public function getCurrentDirectionReverse()
if ($this->getCurrentDirection() == 'asc')
return 'desc';
elseif ($this->getCurrentDirection() == 'desc')
return 'asc';
else
return $this->getCurrentDirection();
edited Jan 5 '17 at 11:28
Volvox
1084
1084
answered Sep 12 '16 at 11:32
Dinesh SainiDinesh Saini
385217
385217
its works fine but, its removed position sort by option.
– Rajkumar .E
Apr 11 '17 at 13:34
You don't need to create config.php just create a new attribute and set yes for used in sorting at product listing. It will not remove position sort by option.
– Ramkishan Suthar
Oct 20 '17 at 15:06
@Dinesh Saini , I have overrided toolbar block like you said / suggested but sort by option is missing in search page . apart from this anything still missing?
– Pramod Kharade
Dec 7 '17 at 9:13
Hi, I am getting error "Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'qty_ordered ' in 'order clause'" while using this code. Please help with the solution.
– Udit Gupta
Jul 5 '18 at 9:19
add a comment |
its works fine but, its removed position sort by option.
– Rajkumar .E
Apr 11 '17 at 13:34
You don't need to create config.php just create a new attribute and set yes for used in sorting at product listing. It will not remove position sort by option.
– Ramkishan Suthar
Oct 20 '17 at 15:06
@Dinesh Saini , I have overrided toolbar block like you said / suggested but sort by option is missing in search page . apart from this anything still missing?
– Pramod Kharade
Dec 7 '17 at 9:13
Hi, I am getting error "Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'qty_ordered ' in 'order clause'" while using this code. Please help with the solution.
– Udit Gupta
Jul 5 '18 at 9:19
its works fine but, its removed position sort by option.
– Rajkumar .E
Apr 11 '17 at 13:34
its works fine but, its removed position sort by option.
– Rajkumar .E
Apr 11 '17 at 13:34
You don't need to create config.php just create a new attribute and set yes for used in sorting at product listing. It will not remove position sort by option.
– Ramkishan Suthar
Oct 20 '17 at 15:06
You don't need to create config.php just create a new attribute and set yes for used in sorting at product listing. It will not remove position sort by option.
– Ramkishan Suthar
Oct 20 '17 at 15:06
@Dinesh Saini , I have overrided toolbar block like you said / suggested but sort by option is missing in search page . apart from this anything still missing?
– Pramod Kharade
Dec 7 '17 at 9:13
@Dinesh Saini , I have overrided toolbar block like you said / suggested but sort by option is missing in search page . apart from this anything still missing?
– Pramod Kharade
Dec 7 '17 at 9:13
Hi, I am getting error "Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'qty_ordered ' in 'order clause'" while using this code. Please help with the solution.
– Udit Gupta
Jul 5 '18 at 9:19
Hi, I am getting error "Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'qty_ordered ' in 'order clause'" while using this code. Please help with the solution.
– Udit Gupta
Jul 5 '18 at 9:19
add a comment |
Here is an easy clean way to achieve this without overriding Magento core.
Create NameSpaceModuleNameetcfrontenddi.xml file with current configuration:
<!-- Adding Sort by Bestsellers functionality -->
<type name="MagentoCatalogBlockProductProductListToolbar">
<plugin name="before_set_collection" type="NameSpaceModuleNamePluginCatalogProductSortingBestsellers" />
</type>
<type name="MagentoCatalogModelConfig">
<plugin name="after_get_available_orders" type="NameSpaceModuleNamePluginCatalogProductSortingBestsellers" />
</type>
Then create plugin class NameSpaceModuleNamePluginCatalogProductSortingBestsellers.php:
namespace NameSpaceModuleNamePluginCatalogProductSorting;
use MagentoCatalogBlockProductProductListToolbar;
use MagentoCatalogModelConfig;
use MagentoFrameworkDataCollection;
class Bestsellers
/**
* Bestsellers sorting attribute
*/
const BESTSELLERS_SORT_BY = 'bestsellers';
/**
* @param Config $subject
* @param $result
* @return array
*/
public function afterGetAttributeUsedForSortByArray(Config $subject, $result)
return array_merge($result, [self::BESTSELLERS_SORT_BY => __('Bestsellers')]);
/**
* @param Toolbar $subject
* @param Collection $collection
*/
public function beforeSetCollection(Toolbar $subject, Collection $collection)
if ($subject->getCurrentOrder() == self::BESTSELLERS_SORT_BY)
$collection->getSelect()->joinLeft(
'sales_order_item',
'e.entity_id = sales_order_item.product_id',
array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)'))
->group('e.entity_id')
->order('qty_ordered '.$subject->getCurrentDirection());
And enjoy =)
add a comment |
Here is an easy clean way to achieve this without overriding Magento core.
Create NameSpaceModuleNameetcfrontenddi.xml file with current configuration:
<!-- Adding Sort by Bestsellers functionality -->
<type name="MagentoCatalogBlockProductProductListToolbar">
<plugin name="before_set_collection" type="NameSpaceModuleNamePluginCatalogProductSortingBestsellers" />
</type>
<type name="MagentoCatalogModelConfig">
<plugin name="after_get_available_orders" type="NameSpaceModuleNamePluginCatalogProductSortingBestsellers" />
</type>
Then create plugin class NameSpaceModuleNamePluginCatalogProductSortingBestsellers.php:
namespace NameSpaceModuleNamePluginCatalogProductSorting;
use MagentoCatalogBlockProductProductListToolbar;
use MagentoCatalogModelConfig;
use MagentoFrameworkDataCollection;
class Bestsellers
/**
* Bestsellers sorting attribute
*/
const BESTSELLERS_SORT_BY = 'bestsellers';
/**
* @param Config $subject
* @param $result
* @return array
*/
public function afterGetAttributeUsedForSortByArray(Config $subject, $result)
return array_merge($result, [self::BESTSELLERS_SORT_BY => __('Bestsellers')]);
/**
* @param Toolbar $subject
* @param Collection $collection
*/
public function beforeSetCollection(Toolbar $subject, Collection $collection)
if ($subject->getCurrentOrder() == self::BESTSELLERS_SORT_BY)
$collection->getSelect()->joinLeft(
'sales_order_item',
'e.entity_id = sales_order_item.product_id',
array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)'))
->group('e.entity_id')
->order('qty_ordered '.$subject->getCurrentDirection());
And enjoy =)
add a comment |
Here is an easy clean way to achieve this without overriding Magento core.
Create NameSpaceModuleNameetcfrontenddi.xml file with current configuration:
<!-- Adding Sort by Bestsellers functionality -->
<type name="MagentoCatalogBlockProductProductListToolbar">
<plugin name="before_set_collection" type="NameSpaceModuleNamePluginCatalogProductSortingBestsellers" />
</type>
<type name="MagentoCatalogModelConfig">
<plugin name="after_get_available_orders" type="NameSpaceModuleNamePluginCatalogProductSortingBestsellers" />
</type>
Then create plugin class NameSpaceModuleNamePluginCatalogProductSortingBestsellers.php:
namespace NameSpaceModuleNamePluginCatalogProductSorting;
use MagentoCatalogBlockProductProductListToolbar;
use MagentoCatalogModelConfig;
use MagentoFrameworkDataCollection;
class Bestsellers
/**
* Bestsellers sorting attribute
*/
const BESTSELLERS_SORT_BY = 'bestsellers';
/**
* @param Config $subject
* @param $result
* @return array
*/
public function afterGetAttributeUsedForSortByArray(Config $subject, $result)
return array_merge($result, [self::BESTSELLERS_SORT_BY => __('Bestsellers')]);
/**
* @param Toolbar $subject
* @param Collection $collection
*/
public function beforeSetCollection(Toolbar $subject, Collection $collection)
if ($subject->getCurrentOrder() == self::BESTSELLERS_SORT_BY)
$collection->getSelect()->joinLeft(
'sales_order_item',
'e.entity_id = sales_order_item.product_id',
array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)'))
->group('e.entity_id')
->order('qty_ordered '.$subject->getCurrentDirection());
And enjoy =)
Here is an easy clean way to achieve this without overriding Magento core.
Create NameSpaceModuleNameetcfrontenddi.xml file with current configuration:
<!-- Adding Sort by Bestsellers functionality -->
<type name="MagentoCatalogBlockProductProductListToolbar">
<plugin name="before_set_collection" type="NameSpaceModuleNamePluginCatalogProductSortingBestsellers" />
</type>
<type name="MagentoCatalogModelConfig">
<plugin name="after_get_available_orders" type="NameSpaceModuleNamePluginCatalogProductSortingBestsellers" />
</type>
Then create plugin class NameSpaceModuleNamePluginCatalogProductSortingBestsellers.php:
namespace NameSpaceModuleNamePluginCatalogProductSorting;
use MagentoCatalogBlockProductProductListToolbar;
use MagentoCatalogModelConfig;
use MagentoFrameworkDataCollection;
class Bestsellers
/**
* Bestsellers sorting attribute
*/
const BESTSELLERS_SORT_BY = 'bestsellers';
/**
* @param Config $subject
* @param $result
* @return array
*/
public function afterGetAttributeUsedForSortByArray(Config $subject, $result)
return array_merge($result, [self::BESTSELLERS_SORT_BY => __('Bestsellers')]);
/**
* @param Toolbar $subject
* @param Collection $collection
*/
public function beforeSetCollection(Toolbar $subject, Collection $collection)
if ($subject->getCurrentOrder() == self::BESTSELLERS_SORT_BY)
$collection->getSelect()->joinLeft(
'sales_order_item',
'e.entity_id = sales_order_item.product_id',
array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)'))
->group('e.entity_id')
->order('qty_ordered '.$subject->getCurrentDirection());
And enjoy =)
answered Jun 22 '18 at 9:26
Pavel PanchyshnyyPavel Panchyshnyy
111
111
add a comment |
add a comment |
The drawback of using sales_order_item.qty_ordered is lifetime sales, i.e. products with high recent sales will be in bottom of page.
I suggest create new index table, with product_id, SUM(qty_ordered) during last 30 days and sort by these values. Plus add second sorting factor by adding date.
Similar solution was implemented in Intelligent Sorting Extension

add a comment |
The drawback of using sales_order_item.qty_ordered is lifetime sales, i.e. products with high recent sales will be in bottom of page.
I suggest create new index table, with product_id, SUM(qty_ordered) during last 30 days and sort by these values. Plus add second sorting factor by adding date.
Similar solution was implemented in Intelligent Sorting Extension

add a comment |
The drawback of using sales_order_item.qty_ordered is lifetime sales, i.e. products with high recent sales will be in bottom of page.
I suggest create new index table, with product_id, SUM(qty_ordered) during last 30 days and sort by these values. Plus add second sorting factor by adding date.
Similar solution was implemented in Intelligent Sorting Extension

The drawback of using sales_order_item.qty_ordered is lifetime sales, i.e. products with high recent sales will be in bottom of page.
I suggest create new index table, with product_id, SUM(qty_ordered) during last 30 days and sort by these values. Plus add second sorting factor by adding date.
Similar solution was implemented in Intelligent Sorting Extension

answered 11 hours ago
AlexAlex
45629
45629
add a comment |
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f135871%2fmagento-2-add-sort-by-best-sellers-option-on-category-products-litsing-page%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown