Hello Magento Folks,
What are you all up to? Welcome again to the Magento tutorial blog where today’s topic is How to get Current Product in Magento 2.
Many a time you need to get current product details in Magento 2. The current product information like product id, product name, and many other details are displayed on the product page. There are several ways to get current product details. As we know that Magento is built with many features in that case it also provides a feature in which the registry is included for storing data of the current product.
Let’s start with the steps to Get Current Product in Magento 2.
Step 1: Create one block file on our custom extension
add Blockname.php in the following path
app\code\Vendor\Extension\Block\Blockname.php
Now add the following code
<?php namespace Vendor\Extension\Block; use Magento\Framework\View\Element\Template; class Blockname extends Template { protected $_registry; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Framework\Registry $registry, ) { $this->_registry = $registry; parent::__construct($context); } public function getCurrentProduct() { return $this->_registry->registry('current_product'); } }
Step 2: Now, we will get the current product in the template phtml file
// print current product data if ($currentProduct = $block->getCurrentProduct()) { echo $currentProduct->getName() . '<br />'; echo $currentProduct->getSku() . '<br />'; echo $currentProduct->getFinalPrice() . '<br />'; echo $currentProduct->getProductUrl() . '<br />'; print_r ($currentProduct->getCategoryIds()) . '<br />'; }
That’s It
The above described is the easiest way to Get Current Product in Magento 2. Also, share the article with your Magento friends and colleagues. If you have any issues related to Magento 2 then write them down in the comment section below I will solve them for you. Stay tuned and Staf safe.
Happy Coding
MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…
In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…
Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…
The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…
Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…
If you are a Shopify admin, using a Shopify Balance Account for your business revenue…