1

I am trying to find a solution to what seems to be a FPC-linked issue.

In my code I am using the following method in order to get the current product ID from a Product page.

$this->catalogSession->getData('last_viewed_product_id')

This worked just fine until I tried it on a website with Full Page Cache: in this case, it returns an empty value (maybe because the session data cannot be accessed from cache).

Does anyone know an alternative method to get the product ID from the current context?

I have tried this alternative synthax: $_SESSION['catalog']['last_viewed_product_id'];

Maxime G
  • 31
  • 2
  • When fpc is enabled session depersonalization come into play. For catalog session it is Magento\Catalog\Model\Layout\DepersonalizePlugin and it clears the storage. This is why last_viewed_product_id is empty. – LucScu Apr 18 '23 at 10:38

1 Answers1

2

While not the best solution and definitely not best practice, you can use objectmanager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$id = $product->getId();

This will get you the id but, as stated above, it's not suggested and you should create a block and inject the registry there and call it in your code. You can see this post https://meetanshi.com/blog/get-current-product-id-in-magento-2/

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83