How to Get Current Product in Magento 2

If you are finding a way to get current product in magento 2 then you are in a right place. This article is all about what you are looking for.

I assume that you already have module. So, first you need to create one block file, if you already have it then use that block and paste the below code.

Copy
namespace Devhooks\Module\Block;
class Module extends \Magento\Framework\View\Element\Template
{
    protected $registry;

    public function __construct(
        \Magento\Backend\Block\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');
    }

}

In above code we have used \Magento\Framework\Registry Magento registry to get current product. Now, we'll get that on our .phtml file.

Copy
if ($currentProduct = $block->getCurrentProduct()) {
    echo $currentProduct->getName() . '<br />';
    echo $currentProduct->getSku() . '<br />';
}

In above code we have echo Name and SKU attributes but you can get it all other as well.

Finally, we are done, let's flush or refresh cache and test the result.

Bingo!!

I hope this post helped you to find what you were looking for. Bookmark it for your future reference. Do comment below if you have any other questions on that.

P.S. Do share this note with your team.

Review other articles maybe it'll help you too.



Search
Recent Posts
    Tags
    Newsletter
    SocialFollow on Twitter
    Visit now!