Displaying Recently Viewed Products is a great way to improve user experience and boost conversions. Magento 2 provides a built‑in approach for this, but many developers still rely on older methods that are now deprecated. Let’s walk through the correct way to implement it.
Deprecated Approach
In older Magento versions, developers often used direct block creation in .phtml files:
<?php
echo $this->getLayout()
->createBlock("Magento\\Reports\\Block\\Product\\Widget\\Viewed")
->setDisplayType("recently.view.products")
->setProductsCount("5")
->setTemplate("widget/viewed/content/viewed_list.phtml")
->toHtml();
?>
This method is not recommended anymore because it doesn’t play well with Full Page Cache (FPC) and can cause performance issues.
Recommended Approach (KnockoutJS + Layout XML)
Magento now uses KnockoutJS and UI Components for Recently Viewed Products. To add the block via layout XML, use the Magento\Catalog\Block\Widget\RecentlyViewed class:
<block class="Magento\Catalog\Block\Widget\RecentlyViewed"
name="recently_viewed"
template="Magento_Catalog::product/widget/viewed/grid.phtml"
after="-">
<arguments>
<argument name="uiComponent" xsi:type="string">widget_recently_viewed</argument>
<argument name="page_size" xsi:type="number">4</argument>
</arguments>
</block>
Advanced Configuration
You can customize the block further by specifying which attributes and buttons to display:
<block class="Magento\Catalog\Block\Widget\RecentlyViewed"
name="recently_viewed"
template="Magento_Catalog::product/widget/viewed/grid.phtml"
after="-">
<arguments>
<argument name="uiComponent" xsi:type="string">widget_recently_viewed</argument>
<argument name="page_size" xsi:type="number">4</argument>
<argument name="show_attributes" xsi:type="string">name,image,price,learn_more</argument>
<argument name="show_buttons" xsi:type="string">add_to_cart,add_to_compare,add_to_wishlist</argument>
</arguments>
</block>
Important: Values for show_attributes and show_buttons must be comma‑delimited strings without spaces. Arrays or spaced values won’t work because of how the UI Component parses data before Knockout renders it.
Why This Approach?
- Cache‑safe → Works properly with Full Page Cache.
- Flexible → Easy to configure attributes and buttons.
- Future‑proof → Uses Magento’s recommended KnockoutJS + UI Component approach.
- No deprecated instructions → Avoids the old
actionXML instruction, which is now deprecated.
Conclusion
If you want to add Recently Viewed Products in Magento 2, always use the Magento\Catalog\Block\Widget\RecentlyViewed block via layout XML. It’s the most reliable, cache‑friendly, and customizable way to implement this feature.
Happy Coding!