Get Current Category and Current Product Detail Magento2

Home / Magento2 / Get Current Category and Current Product Detail Magento2

There are two ways to get or find the current category and current product detail any phtml file.

<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product
    echo $product->getId();
    echo $product->getName();
?>

Or you can try to get other way using your custom module block file.

app/code/JWD/WelcomeWorld/Block/WelcomeWorld.php

<?php namespace JWD\WelcomeWorld\Block; class WelcomeWorld 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');
    }   

}
?>

Look at output or print using below code:

<?php // print current category data $currentCategory = $block->getCurrentCategory();
echo $currentCategory->getName() . '
';
echo $currentCategory->getUrl() . '
';        
 
// print current product data
$currentProduct = $block->getCurrentProduct();
echo $currentProduct->getName() . '
';
echo $currentProduct->getSku() . '
';
echo $currentProduct->getFinalPrice() . '
';
echo $currentProduct->getProductUrl() . '
';
print_r ($currentProduct->getCategoryIds()) . '
';
?>

 

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *