Magento allows you to create and configure 6 different product types in the admin panel. Each product has a unique name, ID, and other details related to it. So, after you learn how to get current category, you have to know how to get current product in Magento 2.
Post Contents [hide]
Get Current Product in Magento 2
To get current product details you need to use Registry.
<?php
namespace VendorName\ModuleName\Folder;
class Example
{
private $registry;
public function __construct(
\Magento\Framework\Registry $registry
) {
$this->registry = $registry;
}
public function getCurrentProduct()
{
return $this->registry->registry('current_product');
}
}
?>
And now you can use getCurrentProduct() method:
// print current product data
if ($currentProduct = $example->getCurrentProduct()) {
echo $currentProduct->getName() . '<br />';
echo $currentProduct->getSku() . '<br />';
echo $currentProduct->getFinalPrice() . '<br />';
echo $currentProduct->getProductUrl() . '<br />';
print_r ($currentProduct->getCategoryIds()) . '<br />';
}
Get Current Product ID in Magento 2
If case you want to get current product ID in Magento you can use the following method:
<?php
$currentProduct = $block->getCurrentProduct();
if ($currentProduct)
echo $currentProduct->getId();
} else {
echo 'There is no current product';
}
?>
You can also use object manager.
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get(\Magento\Framework\Registry::class)->registry('current_product'); //get current product
echo $product->getId();
?>
Note: you should avoid using the ObjectManager in your code directly since it hides real dependencies of the class.