How to Get Recently Viewed Product Collection of a Customer in Magento 2?

Displaying recently viewed products is extremely important for all kinds of eCommerce stores.

It enhances customer experience and also increases the chances of sales.

Now, the recently viewed products are generally displayed based on the number of times a product has been seen by a customer.

And in this tutorial, we will teach you how to get the recently viewed product collection of a customer programmatically.

How to Get Recently Viewed Product Collection of a Customer in Programmatically Magento 2?

Step #1

To get the recently viewed product collection of a customer, we will first have to create a RecentProduct.php file in app/code/MageDelight/RecentProductColl/Block/ directory and add the following code:

<?php

namespace MageDelight\RecentProductColl\Block;

class RecentlyProduct extends \Magento\Framework\View\Element\Template

{

    /**

     * @var \Magento\Reports\Block\Product\Viewed

     */

    protected $recentlyViewed;

    /**

     * @param \Magento\Framework\View\Element\Template\Context $context

     * @param \Magento\Reports\Block\Product\Viewed            $recentlyViewed

     * @param array                                            $data

     */

    public function __construct(

       \Magento\Framework\View\Element\Template\Context $context,

       \Magento\Reports\Block\Product\Viewed $recentlyViewed,

       array $data = []

    ) {

       $this->recentlyViewed = $recentlyViewed;

       parent::__construct($context, $data);

    }

    /**

     * Get Collection Recently Viewed product

     * @return mixed

     */

    public function getRecentViewCollection()

    {

       return $this->recentlyViewed->getItemsCollection()->load();

    }

}

?>

Step #2

The next step is to call the block function in your phtml file as shown below:

<?php

$collection = $block->getRecentViewCollection();

foreach ($collection as $product) {

    echo $product->getName(). '<br />';

}

Now, you can also use the above block function in model, helper, controller, and so on by simply injecting MageDelight\RecentProductColl\Block\RecentlyProduct in construct.

Step #3

The last step is to just clean the cache and test the output.

Upon executing, you will see the recently viewed product collection of customers.

Concluding Thoughts…

That’s it!

This is how easy it is to d.

We hope you found this tutorial easy to understand and helpful.

If you have any questions, please share them in the comments below. And if you need our professional help, feel free to contact us anytime.

Also read: