3

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
    )
    {
        parent::__construct($context);
        $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.

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

3 Answers 3

0

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.

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

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>
            </action>
        </block>
1
  • 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. Commented Feb 21, 2019 at 13:04
-1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.