Magento 2.1 Product View – Fix Current Product Showing as Recently Viewed

magento-2.1magento2product

I've got a problem with my Magento 2.1.4 store. I added recently viewed products block to the product page, but it keeps showing product I''m currently viewing as the 1st recently viewed product (example below).

Please help, I can't figure out why does it happen.

Code that adds the recently viewed product block

<referenceContainer name="content.aside">
    <block class="Magento\Reports\Block\Product\Widget\Viewed" name="related.recently.viewed"
           before="catalog.product.related" after="-"
           template="Magento_Reports::widget/viewed/content/viewed_grid.phtml">
        <argument method="setLimit">
            <argument name="limit" xsi:type="number">4</argument>
        </argument>
    </block>
</referenceContainer>

Example:
Recently viewed product

Best Answer

Found a solution - I'm going to share here in case someone needs it.

You need to overwrite Magento\Reports\Block\Product\Widget\Viewed block and make sure to change this in catalog_product_view.xml.

In the overwritten block add method:

/**
 * Method returns array of recently viewed products without parent product
 *
 * @param array $recentlyViewedProducts
 *
 * @return array
 */
public function removeCurrentProductFromRecentlyViewed(array $recentlyViewedProducts)
{
    $parentProductId = $this->catalogSession->getlastViewedProductId();

    /** @var Product $product */
    foreach ($recentlyViewedProducts as $product) {
        if ((count($recentlyViewedProducts) == 1) && ($product->getId() == $parentProductId)) {
            return [];
        } elseif ($product->getId() == $parentProductId) {
            unset($recentlyViewedProducts[$product->getId()]);
        }
    }

    return $recentlyViewedProducts;
}

This get's current product ID and removes it from the array.

In viewed_grid.phtml you need to add the following section in the if ($exist = ($block->getRecentlyViewedProducts() && $block->getRecentlyViewedProducts()->getSize())) ... code:

$items = $block->getRecentlyViewedProducts();
$itemsWithoutParentProduct = $block->removeCurrentProductFromRecentlyViewed($items->getItems());
$items->removeAllItems();

$exist = false;

if (!count($itemsWithoutParentProduct) == 0) {
    foreach ($itemsWithoutParentProduct as $item) {
        $items->addItem($item);
    }

    $exist = true;
}

And it's done! Good luck everybody.

Related Topic