Get current product in Magento 2

Today I will show you how get current product in Magento 2. It will help you do something that is not available in Magento 2.

Create a block

<?php
namespace Magepow\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();
?>