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.

  • You need this on product detail page? – Amit Naraniwal Feb 21 '19 at 7:06
  • @AmitNaraniwal Yes – Vinoth S Feb 21 '19 at 10:55
  • you can do this using xml see my answer below. – Amit Naraniwal Feb 21 '19 at 11:01
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.

  • Thanks for your solution. But providing limit 6 to get 5 products seems inconsistent. – Vinoth S Feb 21 '19 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>
  • 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. – Vinoth S Feb 21 '19 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, privacy policy and cookie policy

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