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