Magento 2 – How to Get Most Viewed Products

magento2reportsview

How do I get most viewed products in custom Magento2? I already found the workaround for top sellers but I do not get nothing about views

Best Answer

By default, Magento 2 shows the most viewed product in Magento Admin > DASHBOARD > choose tab Most Viewed Products. The _prepareCollection() method in vendor/magento/module-backend/Block/Dashboard/Tab/Products/Viewed.php is used for selecting products.

We can copy some code lines from _prepareCollection() above. For example, in your block, use the following code below:

class Index extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Reports\Model\ResourceModel\Product\CollectionFactory
     */
    protected $_productsFactory;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory,
        array $data = []
    ) {
        $this->_productsFactory = $productsFactory;
        parent::__construct($context, $data);
    }

    /**
     * Getting most viewed products
     */
    public function getCollection()
    {

        $currentStoreId = $this->_storeManager->getStore()->getId();

        $collection = $this->_productsFactory->create()
        ->addAttributeToSelect(
            '*'
        )->addViewsCount()->setStoreId(
                $currentStoreId
        )->addStoreFilter(
                $currentStoreId
        );
        $items = $collection->getItems();
        return $items;
    }
}

The initial class \Magento\Reports\Model\ResourceModel\Product\CollectionFactory is the most important class because this class will get our products report. The getCollection method will return the most viewed items by current store.

In your template, you can get the items. For example:

<?php
    $items = $this->getCollection();
    foreach($items as $item) {
        echo $item->getName() .'<br/>';
    }
?>
Related Topic