:::: MENU ::::

Magento 2 most viewed product collection

Magento 2 most viewed product collection

Let’s talk about using report collection so today we talk about how to get Magento 2 most viewed product collection. Most viewed production collection in depend on number of time product viewed by user. First we have to inject the Reports\ProductCollection in you block or helper any other file you want to use it. So let start with coding. In this example I am going to inject into my block.

Step 1: Create a block file

<?php
  /**
  * Simple Hello World Module
  *
  * @category QaisarSatti
  * @package  QaisarSatti_HelloWorld
  * @author   Muhammad Qaisar Satti
  * @Email    [email protected]
  *
  */

namespace QaisarSatti\HelloWorld\Block;
class BestSeller extends \Magento\Framework\View\Element\Template
{
 
  protected $_collectionFactory;
  protected $_productsFactory;
   public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory,
    array $data = []
   ) {
 
        $this->_productsFactory = $productsFactory;
    parent::__construct($context, $data);
   }
public function getMostViewedData(){
   
    $mostViewedCollection = $this->_productsFactory->create()->addViewsCount();  
    return $mostViewedCollection;
   }
}

Step 2: Show Output

Getting collection in phtml file from block.

<!--/**
  * Simple Hello World Module
  *
  * @category QaisarSatti
  * @package  QaisarSatti_HelloWorld
  * @author   Muhammad Qaisar Satti
  * @Email    [email protected]
  *
  */
-->
  <?php
      $mostViewedProduct =  $block->getMostViewedData(); ?>
      <h1>Most Viewed Collection.....</h1>
      <ul>
          <?php foreach ($mostViewedProduct as $viewedProduct) {
              ?>
              <li><?php echo $viewedProduct>getSku();?>--<?php echo $viewedProduct>getViews();?></li>
          <?php } ?>
</ul>
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


2 Comments

  • Reply Saurabh Mishra |

    Hi Dear,
    I need your help, actually, we need DB table name where save the most_viewed counting information. Actually, we need SQL query so that we can run our database and can get the result.

So, what do you think ?