Hello Everyone,
In this blog, we will learn about how to get Current Product in Magento 2.
Product Collection means showing the items in your Magento 2 Store when you run the command.
Without wasting your time, let us guide you straight away. Follow the easy step given below to get the Current Product in Magento 2.
STEPS FOR GET CURRENT PRODUCT IN MAGENTO 2
Step 1: Create Example.php file
app/code/Vendor/Extension/Block/Example.php
<?php
namespace Vendor\Extension\Block;
class Example extends \Magento\Framework\View\Element\Template
{
protected $registry;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
array $data = []
)
{
$this->registry = $registry;
parent::__construct($context, $data);
}
public function getCurrentProduct()
{
return $this->registry->registry('current_product');
}
}
Now We get Current Product in .phtml file.
if ($currentProduct = $block->getCurrentProduct()) {
echo $currentProduct->getName() . '<br />';
echo $currentProduct->getSku() . '<br />';
}
In above code we get Name and SKU attributes but you can get all other.
Final Thoughts:
So this was the easiest way which we have told you in this blog. This is how you can get Current Product in Magento 2. Hope you liked the blog.
So quickly go to the comment box and tell me how you like this blog?
Stay tuned with us on our site to get new updates of Magento.
Thanks for reading and visiting our site.
