Magento, Magento 2

Magento 2 : Get Recently Viewed Product Collection of Customer

Magento 2 Get Recently Viewed Product Collection of Customer

In this tutorial, Today I will explain you about how to get recently viewed product collection of customer programmatically in Magento 2.

In your store, Display recently viewed product is most important role to successful of your Magento store. It display based on number of time product page viewed by user. It will also helpful for enhance shopping experience of customer. Sometimes, people want to get recently viewed product collection of customer programmatically. After that, they want to perform some actions based on that collection. They also want to customise widget based on that collection.

But, there are many people face trouble to get recently viewed product collection of customer. So, Let’s follow the steps to get collection of recent viewed product.

You may also like this :

Get Recently Viewed Product Collection of Customer in Magento 2 :

1) Create RecentlyProduct.php block file at app/code/RH/RecentProductColl/Block/ and paste the below code:

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\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();
    }
}
?>

2) Now, you can call that block function to your phtml file like this below way :

<?php
/**
 * Created By : Rohan Hapani
 */
$collection = $block->getRecentViewCollection();

foreach ($collection as $product)
{
     echo $product->getName(). '<br />';
}

You can also use this block function in helper, model, controller etc. by inject RH\RecentProductColl\Block\RecentlyProduct in construct.

Now, just clean cache and test output.

I hope this blog will helpful for easily understand about how to get recently viewed product data of customer in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution 🙂

 

Tagged ,