Magento 2 Magento 2 Tutorials

How to Get Current Product ID in Magento 2?

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Loading...Loading...
How to Get Current Product ID in Magento 2

Magento 2 brings in a large number of features to build a fully-functional feature-rich eCommerce store that allows you to customize your store as per your business requirements. The admin panel of this platform can be easily customized and helps you build according to the requirement. Magento lets you customize the admin panel as well as the frontend using various tactics. 

To know how to get a current product ID is one of the basic necessities while applying product-related customization. In Magento 2, the admin can create 6 different types of products, and every time a product is created, there is a unique product ID generated. 

Knowing a product ID helps when you want a product page with totally unique look and feel different to the default product pages of Magento 2. There are two methods to get the current product ID:

  • Using object manager
  • Using block

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();
?>

Using Block

<?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');
}
}

?>

Now, call the function in your .phtml file:

<?php
$currentProduct = $block->getCurrentProduct();
echo $currentProduct->getId();
?>

We hope that we cleared all the doubts and provided all the necessary information regarding getting the current product ID programmatically in Magento 2. If there is any doubt or if you get stuck at any point, feel free to reach us out. Our experts will be happy to assist.

You may also like
Boost Traffic and Visibility in 2021 using the SEO Tips
Boost Traffic and Visibility in 2021 using the SEO Tips
What is SaaS?
What is SaaS? Top 5 World Best SaaS B2B companies?

Leave Your Comment

Your Comment*

Your Name*