Get recently viewed products excluding particular product ID in Magento 2
-
19-02-2021 - |
Question
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.
Solution 3
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.
OTHER TIPS
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.
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>