How to Get Current Product ID in Magento 2

Magento 2 is a flexible and feature-rich eCommerce platform with many robust features that allow you to customize your online store as your business requirement!

You can customize its admin panel as well as frontend using various tactics. One of the basic requirements while applying product-related customization is to get current product ID in Magento 2.

The admin can create six different types of products in Magento 2 store, and each time when a product is created, a unique id gets generated for that product.

Now, what if you want a product page with a unique look and feel for the particular product than the default product page of Magento 2?

In such a case, you have to get the product id of that product before doing further customization! 

One can get the current product Id using two methods:

  • Using object manager
  • Using block

However, it is best practice not to reference the object manager class directly. You can use one of the below methods as per your business requirements.

Besides, you may also need to get parent product id in Magento 2, you can refer to my solution.

Method to Get Current Product ID in Magento 2

1. Using Object Manager

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product
echo $product->getId();
?>

2. Using block

  • Use the below code in your block file.
<?php

namespace Vendor\Module\Block;
class BlockClass extends \Magento\Framework\View\Element\Template
{
    protected $registry;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    )
    {
        $this->registry = $registry;
        parent::__construct($context, $data);
    }

    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

    public function getCurrentProduct()
    {
        return $this->_registry->registry('current_product');
    }
}

?>
  • Call function in your .phtml file:
<?php
$currentProduct = $block->getCurrentProduct();
echo $currentProduct->getId();
?>

That’s it.

Do consider sharing this post with Magento Community via social media.

Thank you.

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...