How to implement sort by “Most viewed” products in Magento 2?

How to Implement sort by most viewed products in magento 2

Almost every eCommerce store is filled with thousands of products. If an eCommerce store is not facilitating its customers to navigate and sort the products as per their requirement, there would be a drastic impact on its conversion rates.

Therefore to provide better customer experience, it is must to use sorting extensions in your Magento 2 e-commerce website. The product catalog can be sorted based upon the following options:

  • Most Viewed
  • What’s New (Latest Products Added)
  • Discount
  • Sort by Bestseller
  • Price: Low to High
  • Price: High to Low
  • Faster delivery, etc.

 

The Magento 2 Development Services allow the developer/ Admin to select multiple sort options from the backend.

Guide to implement sort by “Most Viewed” products in Magento 2

Step 1: First, we need to create two plugins. Before creating the plugins, we first need to declare the plugin in the di.xml file of the module.

[Vendor]/[ModuleName]/etc/frontend/di.xml

<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:ObjectManager/etc/config.xsd”>

<type name=”Magento\Catalog\Model\Config”>

<plugin name=”sortby_add_custom_option” type=”[Vendor]\[ModuleName]\Plugin\Model\Config” />

</type>

<type name=”Magento\Catalog\Block\Product\ProductList\Toolbar”>

<plugin name=”sortby_extend_default_sort_filters” type=”[Vendor]\[ModuleName]\Plugin\Block\Toolbar” />

</type>

</config>

Step 2: Create the first plugin

[Vendor]\[ModuleName]\Plugin\Model\Config.php

<?phpnamespace [Vendor]\[ModuleName]\Plugin\Model;

class Config

{

/**

* Add custom Sort By option

*

* @param \Magento\Catalog\Model\Config $catalogConfig

* @param array $options

* @return array []

* @SuppressWarnings(PHPMD.UnusedFormalParameter)

*/

public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig, $options)

{

// new sorting option

$customOption[‘most_viewed’] = __(‘Most Viewed’);

// merge default sorting options with custom options

$options = array_merge($customOption, $options);

return $options;

}

/**     * This method is optional. Use it to set Most Viewed as the default

* sorting option in the category view page

*

* @param \Magento\Catalog\Model\Config $catalogConfig

* @return string

* @SuppressWarnings(PHPMD.UnusedFormalParameter)

*/

public function afterGetProductListDefaultSortBy(\Magento\Catalog\Model\Config $catalogConfig)    {

return ‘most_viewed’;

}

}

Step 3: Create the second plugin

[Vendor]\[ModuleName]\Plugin\Block\Toolbar.php

<?phpnamespace [Vendor]\[ModuleName]\Plugin\Block;

use Magento\Framework\App\ResourceConnection;

use Magento\Framework\DB\Select;

/**

* Product list toolbar plugin

*/

class Toolbar

{

const SORT_ORDER_DESC = ‘DESC’;

/**

* @var \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection

*/

protected $_collection = null;

/**

* DB connection

*

* @var \Magento\Framework\DB\Adapter\AdapterInterface

*/

protected $_conn;

/**

* @var boolean

*/

protected $_subQueryApplied = false;

/**

* Constructor

*

* @param \Magento\Framework\App\ResourceConnection $resource

*/

public function __construct(ResourceConnection $resource)

{

$this->_conn = $resource->getConnection(‘catalog’);

}

/**

* Plugin – Used to modify default Sort By filters

*

* @param \Magento\Catalog\Block\Product\ProductList\Toolbar $subject

* @param null $result

* @param \Magento\Framework\Data\Collection $collection

* @return Toolbar

* @SuppressWarnings(PHPMD.UnusedFormalParameter)

*/

public function afterSetCollection(\Magento\Catalog\Block\Product\ProductList\Toolbar $subject,        $result,        $collection

) {

$this->_collection = $collection;

if ($subject->getCurrentOrder() == ‘most_viewed’) {

if (!$this->_subQueryApplied) {

$reportEventTable = $this->_collection->getResource()->getTable(‘report_event’);

$subSelect = $this->_conn->select()->from(

[‘report_event_table’ => $reportEventTable],

‘COUNT(report_event_table.event_id)’

)->where(

‘report_event_table.object_id = e.entity_id’

);

$this->_collection->getSelect()->reset(Select::ORDER)->columns(

[‘views’ => $subSelect]

)->order(

‘views ‘  . self::SORT_ORDER_DESC

);

$this->_subQueryApplied = true;

}

}         return $this;

}

}

Want to have sort by “Most Viewed” feature in your store?

If your e-commerce store is deprived from sort by “Most Viewed” products or other features, talk to our expert team of Magento 2 Developers.

How useful was this post?

Click on a star to rate it!

Average rating

Vote count:

We are sorry that this post was not useful for you!

Let us improve this post!

Leave a Reply

Your email address will not be published. Required fields are marked *