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

3 Answers 3


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
    Commented Jul 5, 2018 at 9:16
  • Am too facing this issue. Did you find any solution for this issue? @UditGupta
    – Quasar M
    Commented Jul 12, 2019 at 13:00

Improved Sorting extension provides the same functionality to sort by newest and most viewed products.


If we need to get the most viewed product through SQL you have to just run this script in SQL and you will get the most view product in Magento-2

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

please comment if you will get any issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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