If you are working on Magento 2 project, then many times you need to get current product object. Magento 2 has several different ways to get it. In this article, I would like to overview two, the most popular, ways. The current product in Magento 2 is stored to Magento registry, with the key current_product. In both ways we will use this registry to get, what we need, but one of the methods is more correct. Let’s begin with the easiest one.
$product = \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Framework\Registry::class)
->registry('current_product');
This code snippet works in almost all code places where you will paste it. The great thing about it is, that this code snippet is in one piece and it’s very easy to use. But there is a better way.
The right way to get current product
According to Magento, it’s not recommended to use object manager. The right way is dependency injection method. As I already mentioned, current product is stored in Magento registry. So we need to include registry object in class constructor and call it directly. Here is the code example how to get current product using dependency injection.
public $registry;
public function __construct(\Magento\Framework\Registry $registry)
{
$this->registry = $registry;
}
$product = $this->registry->registry('current_product');
Code example: how to get current product in .phtml template
Our block class should look like:
<?php
namespace Magetrend\HelloWorld\Block;
class Attachment extends \Magento\Framework\View\Element\Template
{
public $registry;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Registry $registry,
array $data = []
) {
$this->registry = $registry;
parent::__construct($context, $data);
}
public function getCurrentProduct()
{
return $this->registry->registry('current_product');
}
}
then we can make a call in our template .phtml file:
<?php $currentProduct = $block->getCurrentProduct(); ?>
to get product ID, product name or other product information you can use:
<?php echo $currentProduct->getId(); ?>
<?php echo $currentProduct->getName(); ?>
Troubleshooting
No changes in product page
if you have added the code in .phtml file and don’t see any changes in fronted, probably it’s just need to clear the cache.
That’s all for this post. Let me know, in the comments bellow, if something was missed. I will be more than happy to get your feed and append this post.