Magento 2 with Full Page Cache: How to get product ID from a product page?

593 views Asked by At

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'];

1

There are 1 answers

0
Nikos Melis On

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/