[Magento 2] Get current product

Getting the “current product” in Magento 2 is trickier than it was in Magento 1. However, it is like that for a reason: Mage:: is a thing from the past, no more accessing to everything from everywhere (someone I know would say: “this is not logic at all”).

That’s the reason why, in order to get the current product in a product page, you’ll need to use the class Magento\Framework\Registry in your block and add the registry to your construct class. After that, you can create a function that will retrieve the current product from the registry (and call it from your template):

/**
 * Magento 2 Get Product
 * Module Company/Module
 */
namespace Company\Module\Block\Product;

use Magento\Framework\Registry;

...

    public function __construct(
        Registry    $registry,
    ) {
        parent::__construct($registry);
    }

...

/**
     * Get the current product
     *
     * @return Product
     */
    public function getCurrentProduct()
    {
        return $this->registry->registry('current_product');
    }

Leave a Reply

Your email address will not be published.