I am using this Magento 2 add Sort By Best Sellers Option on category products litsing page for Best Seller Products i want to same New Products and Most View Product


Try this:


public function getAttributeUsedForSortByArray()
        $options = ['bestseller' => __('Best Seller'), 'newest' => __('Newest'), 'mostviewed' => __('Most Viewed')];
        foreach ($this->getAttributesUsedForSortBy() as $attribute)
            /* @var $attribute \Magento\Eav\Model\Entity\Attribute\AbstractAttribute */
            $options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();

        return $options;


public function setCollection($collection)
        // bestseller code

        if($this->getCurrentOrder() == "newest")
                ->order('created_at ' . $this->getCurrentDirectionReverse());

        if($this->getCurrentOrder() == "mostviewed")
                'e.entity_id = report_event.object_id',
                array('view_count' => 'COUNT(report_event.event_id)'))
                ->order('view_count ' . $this->getCurrentDirectionReverse());

        $this->_collection = $collection;


        $limit = (int)$this->getLimit();
            $this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
        return $this;
  • Hi, I am getting error "Exception #1 (PDOException): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'view_count ' in 'order clause'" while use this code. Please help with the solution. – Udit Gupta Jul 5 '18 at 9:16
  • Am too facing this issue. Did you find any solution for this issue? @UditGupta – Prabhu M. Jul 12 at 13:00

You can get most viewed product threw SQL you have to just run on phpmyadmin.

SELECT COUNT(report_table_views.event_id) AS `views`, `e`.* FROM `report_event` AS `report_table_views` INNER JOIN `catalog_product_entity` AS `e` ON e.entity_id = report_table_views.object_id AND e.attribute_set_id = '13' WHERE (report_table_views.event_type_id = 1) GROUP BY `e`.`entity_id` HAVING (COUNT(report_table_views.event_id) > 0) ORDER BY `views` DESC

and I am damn sure it will run.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.