Hello Magento Folks?,
How are you all working? Today I am going to help you all in How to Get Most Viewed Product Collection. In case you missed our previously placed article Magento 2: How to Get Best Seller Products Collection.
Let’s Begin?
Introduction:
There are many options provided by Magento for helping the users to choose the best items. Most view products are one of the options that are provided by Magento 2. It helps your Magento 2 store in improving sales. By displaying the Most Viewed Products in your store will help your customers to select the best product. But if you require to display the most viewed product you will have to get the most viewed product collection. Follow the below-given steps to get the Most Viewed Product Collection.
Steps to getting Most Viewed Product Collection:
Step 1: Create one block file on our custom extension
add Blockname.php in following path
app\code\Vendor\Extension\Block\Blockname.php
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 34 35 36 |
<?php namespace Vendor\Extension\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() ->addAttributeToSelect('*') ->addViewsCount() ->setStoreId($currentStoreId) ->addStoreFilter($currentStoreId); return $collection->getItems(); } } |
Step 2: After the above step Insert the below code in phtml file at the following path.
app\code\Vendor\Extension\view\frontend\templates\list.phtml.
1 2 3 4 5 |
<?php $collection = $block->getProductCollection(); foreach ($collection as $_product) { echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />'; } |
Step 3: At last Flush Cache and view the result
Final Words:
Most probably all are able to implement the above-given steps to Get Most Viewed Product Collection in Magento 2. But if you find any difficulties during the implementation then write down your queries in the comment section below I am solving there. Make sure you don’t forget to share the article with your developer friends. Till then stay safe and stay happy.
Happy Coding?