3

How do I get most viewed products in custom Magento2? I already found the workaround for top sellers but I do not get nothing about views

5

By default, Magento 2 shows the most viewed product in Magento Admin > DASHBOARD > choose tab Most Viewed Products. The _prepareCollection() method in vendor/magento/module-backend/Block/Dashboard/Tab/Products/Viewed.php is used for selecting products.

We can copy some code lines from _prepareCollection() above. For example, in your block, use the following code below:

class Index extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Reports\Model\ResourceModel\Product\CollectionFactory
     */
    protected $_productsFactory;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory,
        array $data = []
    ) {
        $this->_productsFactory = $productsFactory;
        parent::__construct($context, $data);
    }

    /**
     * Getting most viewed products
     */
    public function getCollection()
    {

        $currentStoreId = $this->_storeManager->getStore()->getId();

        $collection = $this->_productsFactory->create()
        ->addAttributeToSelect(
            '*'
        )->addViewsCount()->setStoreId(
                $currentStoreId
        )->addStoreFilter(
                $currentStoreId
        );
        $items = $collection->getItems();
        return $items;
    }
}

The initial class \Magento\Reports\Model\ResourceModel\Product\CollectionFactory is the most important class because this class will get our products report. The getCollection method will return the most viewed items by current store.

In your template, you can get the items. For example:

<?php
    $items = $this->getCollection();
    foreach($items as $item) {
        echo $item->getName() .'<br/>';
    }
?>
  • great! thanks a lot. Is it possible to reuse the list template with the resulted collection? – fefe Apr 21 '16 at 7:23
  • Definitely, say yes. We need to override the layout vendor/magento/module-catalog/view/frontend/layout/catalog_category_view.xml. In our custom layout, we add our block and template. For example, <referenceContainer name="content"> <block class="Boolfly\Product\Block\Index" name="most.viewed" as="most.viewed" template="Boolfly_Product::most_viewed_product.phtml" before="-" /> </referenceContainer> – Khoa TruongDinh Apr 21 '16 at 8:27

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.