I need to get recently viewed products for a customer in a product view but excluding the current product the customer is viewing. I have,

class Index extends Action
    protected $recentlyViewed;

    public function __construct(
        Context $context,
        \Magento\Reports\Block\Product\Viewed $recentlyViewed
        $this->recentlyViewed = $recentlyViewed;

    public function execute()
        $recentProducts = $this->recentlyViewed->getItemsCollection()->getData();

This $recentProducts returns particular number of recently viewed products based on the admin configuration. For example, if the limit of recent products is 5, this returns 5 products. But I need 5 products excluding current product.

How can I exclude a particular product by providing it's ID?

Thanks in advance.

  • You need this on product detail page? Feb 21, 2019 at 7:06
  • @AmitNaraniwal Yes Feb 21, 2019 at 10:55
  • you can do this using xml see my answer below. Feb 21, 2019 at 11:01

3 Answers 3


Set limit to 6 if you want 5 products.

Sort collection by descending order

$recentProducts = $this->recentlyViewed->getItemsCollection()->setOrder("index_id","DESC")->getData();

Remove first element of your array

$recentProducts = array_shift($recentProducts);

Now your final collection would skip your current product.

  • Thanks for your solution. But providing limit 6 to get 5 products seems inconsistent. Feb 21, 2019 at 6:57

Add the below code in the layout file catalog_product_view.xml :

<block class="Magento\Reports\Block\Product\Widget\Viewed" after="-" name="recently_viewed" cacheable="false" template="Magento_Reports::widget/viewed/content/viewed_grid.phtml">
            <action method="setPageSize">
                <argument name="page_size" xsi:type="number">4</argument>
  • This looks good to display recent products during page onload. But controller seems to be better option to me, since I'm appending this content using AJAX. Thanks for your solution. Feb 21, 2019 at 13:04

Just add excludeProductIds() filter to collection like,

$recentProducts = $this->recentlyViewed->getItemsCollection()->excludeProductIds($productId)->getData();

This will always return required number of products without including the given productId.

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .