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













4















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










share|improve this question




























    4















    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










    share|improve this question


























      4












      4








      4


      3






      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










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 12 '16 at 10:33







      Dinesh Saini

















      asked Sep 12 '16 at 10:20









      Dinesh SainiDinesh Saini

      385217




      385217




















          3 Answers
          3






          active

          oldest

          votes


















          4














          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();









          share|improve this answer

























          • 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


















          1














          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 =)






          share|improve this answer






























            0














            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



            enter image description here






            share|improve this answer






















              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
              );



              );













              draft saved

              draft discarded


















              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









              4














              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();









              share|improve this answer

























              • 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















              4














              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();









              share|improve this answer

























              • 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













              4












              4








              4







              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();









              share|improve this answer















              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();










              share|improve this answer














              share|improve this answer



              share|improve this answer








              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

















              • 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













              1














              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 =)






              share|improve this answer



























                1














                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 =)






                share|improve this answer

























                  1












                  1








                  1







                  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 =)






                  share|improve this answer













                  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 =)







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jun 22 '18 at 9:26









                  Pavel PanchyshnyyPavel Panchyshnyy

                  111




                  111





















                      0














                      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



                      enter image description here






                      share|improve this answer



























                        0














                        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



                        enter image description here






                        share|improve this answer

























                          0












                          0








                          0







                          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



                          enter image description here






                          share|improve this answer













                          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



                          enter image description here







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 11 hours ago









                          AlexAlex

                          45629




                          45629



























                              draft saved

                              draft discarded
















































                              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.




                              draft saved


                              draft discarded














                              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





















































                              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







                              Popular posts from this blog

                              Bulk add to cart function issuecart vs. mini cart issue … rwd themeRedirect Add to cart button to cart pageAdd to cart issue - Magento 2.1The requested Payment Method is not available When creating an orderM2: reason add-to-cart might not function in production modeAdd to cart issue in some android devicesMagento 2 - custom price can not add to subtotal and grand total after add to cartAdd to cart codeIssue with my cart module on pdp and cart pages, just keeps spinningBulk price and quantity update using rest api

                              БиармияSxpst500bh2ntaf! 3h2r