Magento 2 get current product
This post shows you how to programmatically get current product in Magento 2. This is essentially if you want to display product related content on frontend (for example special banners or overlays).
Magento 2 get current product
Following code shows you how to create a simple class that returns current product:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php namespace MyCompany\MyModule\Helper; class MyModel extends Magento\Framework\App\Helper\AbstractHelper { protected $registry; public function __construct( ... \Magento\Framework\Registry $registry ){ ... $this->registry = $registry; } public function getCurrentProduct() { return $this->registry->registry('current_product'); } ... } |
From \Magento\Framework\Registry you can get useful information like current product. For this you need to inject this class als showed and call registry method with “current_product” string as param. getCurrentProduct() returns a product model if this was called from frontend. You need to change MyCompany, MyModule and MyModel identifiers to your needs.
This is useful for blocks and controllers or helpers that are used from frontend models. You need to check if it is an object, because this obviously does not work as expected if you call this from adminhtml or command line. From a product model you get additional information like
1 2 | $id = $product->getId(); $name = $product->getName(); |
You may need current visited product for activate product dependent frontend decoration or additional product features. This is also useful if you want to track your user and get details of visited products.
This solution is the recommended one! You may find other using object manager. Please note, that using object manager on frontend sites is a bad idea, it slows down your shop. Injecting objects is highly recommended and always the better solution.
Conclusion
I showed you how to programmatically get current product. It is easy to get additional information for every frontend site like current category or current product.