Magento 2 get current product information

Today we talk about how to get Magento 2 current product information like product id, product name and other information on product page. Magneto 2 have feature of registry to store data. That is use to store data between execution of data. Like you want to set data in controller and use it in block or model the registry is best option for that. So let start with getting the product data from registry. Now i use HelloWorld module block example for getting current product.

Create a Block

<?php
namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
    protected $registry;

    public function __construct(  
        \Magento\Framework\Registry $registry,

    )
    {      
        $this->registry = $registry;

    }


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

}
?>

Get product information In your phtml file

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

If you want to get in current product information in phtml you can use following code.

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

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply