how to get the most viewed product collection in your Magento 2 store?

I try with multiple codes but unfortunately, I am not getting any solution.

I try to create a MostViewedProducts.php file in the /Productslider/Block/ folder & paste the code to get the most viewed product collection in the block. but, not working.


namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;

class Blockname 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()

    return $collection->getItems();


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

Add above colllection in the phtml file assigned to block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.