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.

saveCopyzoom_out_map
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.

saveCopyzoom_out_map
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.




Recent Articles
Tags
Newsletter
Chrome Extension
Copyright © 2024 devhooks.in All rights reserved.
Ads OFF toggle_off
wifi_off