This article shows how we can get current category and current product data in Magento 2.
Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of \Magento\Framework\Registry class in the constructor of my module’s block class.
app/code/Chapagain/HelloWorld/Block/HelloWorld.php
<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld 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 _prepareLayout()
{
return parent::_prepareLayout();
}
public function getCurrentCategory()
{
return $this->_registry->registry('current_category');
}
public function getCurrentProduct()
{
return $this->_registry->registry('current_product');
}
}
?>
Printing current category and current product in any template (.phtml) file
// print current category data
$currentCategory = $block->getCurrentCategory();
echo $currentCategory->getName() . '<br />';
echo $currentCategory->getUrl() . '<br />';
// print current product data
$currentProduct = $block->getCurrentProduct();
echo $currentProduct->getName() . '<br />';
echo $currentProduct->getSku() . '<br />';
echo $currentProduct->getFinalPrice() . '<br />';
echo $currentProduct->getProductUrl() . '<br />';
print_r ($currentProduct->getCategoryIds()) . '<br />';
Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
$registry = $objectManager->get('\Magento\Framework\Registry');
$currentCategory = $registry->registry('current_category');
$currentProduct = $registry->registry('current_product');
echo $currentCategory->getName() . '<br />';
echo $currentCategory->getUrl() . '<br />';
echo $currentProduct->getName() . '<br />';
echo $currentProduct->getSku() . '<br />';
echo $currentProduct->getFinalPrice() . '<br />';
echo $currentProduct->getProductUrl() . '<br />';
For more, see:
– MAGENTO_ROOT/vendor/magento/module-catalog/Model/Product.php
– MAGENTO_ROOT/vendor/magento/module-catalog/Model/Category.php
Hope this helps. Thanks.