How to Display Recently Viewed Products Programmatically

It is well known that you can easily display the recently viewed products by adding a widget from the admin area. The alternative way to the widget is to do that programmatically. Let's have a look on that in this post then.

We assume that you would like to display the recently viewed products block the catalog pages after the product list. The block class responsible for the recently viewed products is the Magento\Catalog\Block\Widget\RecentlyViewed. The templates that can be used are depending on the template product view style and can be grid, list or sidebar. These templates are located in the Magento catalog module under product/widget/viewed/ folder. In our example we will use the product/widget/viewed/grid.phtml template.

What we need to do is to update the layout of the category view page adding the recently viewed products block.

As you can see above, there are some arguments needs to be passed in our block class like uiComponent, page_size, show_attributes and show_buttons. The values of the arguments that can be passed, can be found in the widget declaration in vendor/magento/module-catalog/etc/widget.xml for the widget with id catalog_recently_viewed.

Feel free to share this post and ask your questions in the comments below.

Till next time!

DigitalOcean Referral Badge