Get current product in Magento 2
Today we will show you how to get the current product in Magento 2. It will help you do something that is not available in Magento 2.
Posted: August 04, 2020
Today we will show you how to get the 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 the 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();
?>
0 Comment(s)