Question

How to get bestseller and most viewed product in homepage Magento 2?

We have to display bestseller and most viewed product list in homepage slider in magento 2.

Was it helpful?

Solution

For bestseller create a block in __construct get instance of

\Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory,

ex

<?php
namespace Sugarcode\Test\Block;

class Test extends \Magento\Framework\View\Element\Template
{
    protected $_coreRegistry = null;
    protected $_collectionFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
       \Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory,
        array $data = []
    ) {
        $this->_collectionFactory = $collectionFactory;
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }



    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }
    public function getBestSellerData()
    {
        $collection = $this->_collectionFactory->create()->setModel(
            'Magento\Catalog\Model\Product'
        );

        return $collection;
    }       

}

For recently viewed you can use widget from admin side or else you can write custom block with \Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory

Look at:

vendor\magento\module-backend\Block\Dashboard\Tab\Products\Viewed.php

and

vendor\magento\module-backend\Block\Dashboard\Tab\Products\Ordered.php 

OTHER TIPS

Use the following code to view the BEST SELLER as well as MOST VIEWED products in your Magento 2 Slider.

<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();   
$productCollection = $objectManager->create('Magento\Reports\Model\ResourceModel\Report\Collection\Factory'); 
$collection = $productCollection->create('Magento\Sales\Model\ResourceModel\Report\Bestsellers\Collection'); ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top