Magento 2 – Bestseller and Most Viewed Products on Homepage

best-sellermagento2product

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.

Best Answer

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 
Related Topic