How do I get the current product?

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?

Solutions

If you are using Magento 2.1 or major, you can use this helper because the old method was deprecated.

...
use Magento\Catalog\Helper\Data;
...

public function __construct(
        Context $context,
        Data $helper,
        array $data = []
    ){
        $this->context = $context;
        $this->helper = $helper;
        $this->data = $data;
        parent::__construct($context, $data);
    }

...

public function getProduct(){
    if(is_null($this->_product)){
        $this->_product = $this->helper->getProduct();
    }
    return $this->_product;
}

Although other answers are correct, they're not the recommended/proper solution either.

Using the ObjectManager is absolutely prohibited in Magento 2. So please don't rely on this solution, but use proper DI to achieve this instead. To learn how to use DI in Magento 2, see this resource: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/depend-inj.html

Extending AbstractView is not necessary. If you look at the original function in the AbstractView, you can see Magento used the registry to fetch the product. You don't need to extend a specific class to do this, simply inject Magento\Framework\Registry into your constructor and request the "product" registry item.

Full code example:

<?php

// Example = Module namespace, Module = module name, rest of the namespace is just for example only, change this to whatever it is in your case.
namespace Example\Module\Block\Frontend\Catalog\Product\General;

use Magento\Catalog\Model\Product;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template;

class Information extends Template
{

    /**
     * @var Registry
     */
    protected $registry;

    /**
     * @var Product
     */
    private $product;

    public function __construct(Template\Context $context,
                                Registry $registry,
                                array $data)
    {
        $this->registry = $registry;

        parent::__construct($context, $data);
    }


    /**
     * @return Product
     */
    private function getProduct()
    {
        if (is_null($this->product)) {
            $this->product = $this->registry->registry('product');

            if (!$this->product->getId()) {
                throw new LocalizedException(__('Failed to initialize product'));
            }
        }

        return $this->product;
    }

    public function getProductName()
    {
        return $this->getProduct()->getName();
    }

}

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.

Similar questions

Magento 2 - Get configurable product from current product
I can get current product attribute using $product->getAttributes(). How can I get the configurable product list and their corresponding attributes programmatically?
Get current product name in static web template html file on product view page
I want to get the current product name in static html file which is called in product view page like below file app/design/frontend/Vendorname/themename/Aheadworks_AdvancedReviews/web/template/product/view/review/summary/container.html
Magento2: How to get current product parent category on product detail page?
I want to get the current product parent category on the product detail page in Magento2? My Code: But I am not getting the value Any help would be appreciated.
how to get category name of current product (on product detail page) in magento
I used following codes but didn't work for this case: got Fatal error: Call to a member function getName() on a non-object in /app/design/frontend/base/default/template/catalog/product/view.phtml we make some filters and use below mention code in head.phtml: But this only works if you go from a category to a product. If you visit the product page d...
get configurable product attributes labels and id of current product in magento
When I print_r $myArray..it display all labels of color attribute.. I want to display only those attribute (labels and id) which is used by current product.Also my site is using some custom theme I want to enable default configurable options to be displayed with product.currently its not.
Using observer, how to get the current pager with loaded product collection
Using an observer how can i get the current pager block with its loaded product collection on a category page? I want to check the total number of pages on a category page before it is loaded.

Also ask

We use cookies to deliver the best possible experience on our website. By continuing to use this site, accepting or closing this box, you consent to our use of cookies. To learn more, visit our privacy policy.