How to get most viewed products and bestsellers on homepage in Magento 2
To get most viewed products and bestsellers on homepage in Magento 2, create a block in __construct get instance of
\Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory,
for instance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?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; } } |
fore recently viewed you can use widget from admin side or else you can write custom block with
1 |
\Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory |
see
1 |
vendor\magento\module-backend\Block\Dashboard\Tab\Products\Viewed.php vendor\magento\module-backend\Block\Dashboard\Tab\Products\Ordered.php |
Source (