Magento2 – How to Get the Current Product

blocksmagento2phtmlproductproduct-attribute

I'm trying to retrieve the current product's attributes in a block in Magento 2.

I can get a product, like ID 1:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager
               ->create('\Magento\Catalog\Model\ProductRepository')
               ->getById(1);

I don't know how to get the ID of the current product though.

How could I do that?

Best Answer

In order to get the current product, one of the recommended ways is:

  1. Extend or use block class: Magento\Catalog\Block\Product\View\AbstractView.
  2. Get product using: $block->getProduct() in your phtml file.