Magento 2.1 – Sort Product List Page by Most Viewed

magento-2.1magento-2.1.7product-attributeproduct-listsorting

We need to bring most viewed, most subscribed and latest options in the sort menu in product listing page of our magento 2.1 application (magento 2.1.7). I already refered the this link Product List Page Sort by Most View ( can we sort this by page views/hits). As this is for magento 1, most of the classes like Mage is not available in my magento 2.1 app.

Kindly share your suggestions to implement this in magento 2.1 application using code.

Best Answer

If you want to add option in the sort menu then you need to create a plugin as I achieved

1) create di.xml file and the below code

<?xml version="1.0"?>
<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="add_custom_sort" type="Test\MyMagento\Plugin\Catalog\CustomSort" sortOrder="10"/>
    </type>

</config>

2) create CustomSort.php file and the bleow code

<?php
namespace Test\MyMagento\Plugin\Catalog;

class CustomSort
{

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

    $options['mostviewd'] = __('Mostveiwd');
    return $options;

 }

}
Related Topic