0

Method to Get Current Product ID in Magento 2

There two way for this task

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

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

This code add in phtml file where you want to display

 <?php 
$currentProduct = $block->getCurrentProduct();echo $currentProduct->getId();
?>
2
  • where you have trying to access?
    – Amit Bera
    Commented Apr 19, 2022 at 7:41
  • Product details page Commented Apr 19, 2022 at 7:49

1 Answer 1

0

Two things :

  • Number 1, do not use Object manager, this is deprecated from very long time. We use only dependency injection now
  • Number 2 : To get the current product (aka current category) the registry seems to be fine, although there is better version at lower level they will end up using registry too i think. So this code should work, if it's not, it's probable a cache issue. That's why I would suggest you to add in the xml definition of the block and template cacheable=false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.