How to Get Most Viewed Product Collection

Steps to Get Most Viewed Product Collection

Create MostViewedProducts block

Directory

VendorName/ModuleName/Block/MostViewedProducts.php

Content for this file

<?php

namespace VendorName\ModuleName\Block;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\App\Http\Context as HttpContext;
use Magento\Framework\Stdlib\DateTime\DateTime;
use VendorName\ModuleName\Helper\Data;
use VendorName\ModuleName\Model\ResourceModel\Report\Product\CollectionFactory as MostViewedCollectionFactory;
/**
 * Class MostViewedProducts
 * @package VendorName\ModuleName\Block
 */
class MostViewedProducts extends AbstractSlider
{
    /**
     * @var MostViewedCollectionFactory
     */
    protected $_mostViewedProductsFactory;
    /**
     * MostViewedProducts constructor.
     * @param Context $context
     * @param CollectionFactory $productCollectionFactory
     * @param Visibility $catalogProductVisibility
     * @param DateTime $dateTime
     * @param Data $helperData
     * @param HttpContext $httpContext
     * @param MostViewedCollectionFactory $mostViewedProductsFactory
     * @param array $data
     */
    public function __construct(
        Context $context,
        CollectionFactory $productCollectionFactory,
        Visibility $catalogProductVisibility,
        DateTime $dateTime,
        Data $helperData,
        HttpContext $httpContext,
        MostViewedCollectionFactory $mostViewedProductsFactory,
        array $data = []
    ) {
        $this->_mostViewedProductsFactory = $mostViewedProductsFactory;
        parent::__construct($context, $productCollectionFactory, $catalogProductVisibility, $dateTime, $helperData, $httpContext, $data);
    }
    /**
     * Get Product Collection of MostViewed Products
     * @return mixed
     */
    public function getProductCollection()
    {
        $collection = $this->_mostViewedProductsFactory->create()
            ->addAttributeToSelect('*')
            ->setStoreId($this->getStoreId())->addViewsCount()
            ->addStoreFilter($this->getStoreId())
            ->setPageSize($this->getProductsCount());
        return $collection;
    }
}

 

Insert in phtml file

Directory

VendorName/ModuleName/view/frontend/templates/list.phtml

Content for this file

<?php
$collection = $block->getProductCollection();
foreach ($collection as $_product) {
    echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}

 

Flush Cache & Check result

Now flush or clear the cache and check the result, the command:

php bin/magento cache:clean

 

 

If you are looking for Magento Development, visit Magento Development Agency.