1.Create one block file on our custom extension add MostViewedProducts.php in following path
app\code\Vendor\Extension\Block\MostViewedProducts.php
<?php
namespace Vendor\Extension\Block;
use Magento\Framework\View\Element\Template;
class MostViewedProducts extends Template
{
protected $_productsFactory;
protected $_storeManager;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
array $data = []
) {
$this->_productsFactory = $productsFactory;
$this->_storeManager = $storeManager;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$currentStoreId = $this->_storeManager->getStore()->getId();
$collection = $this->_productsFactory->create()
->addAttributeToSelect('*')
->addViewsCount()
->setStoreId($currentStoreId)
->addStoreFilter($currentStoreId);
return $collection->getItems();
}
}
2.Then create list.phtml file on following path
app\code\Vendor\Extension\view\frontend\templates\list.phtml.
<?php
$collection = $block->getProductCollection();
foreach ($collection as $_product) {
echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}
3.Then flush cache and test result.