Magento 2 get current category information

Today we talk about how to get Magento 2 current category information.Information like current category id, current category name and other category information on category page. Magneto 2 have feature of registry to store data. That is use to store data between execution of data. Like you want to set data in controller and use it in block or model the registry is best option for that. So let start with getting the category data from registry. Now i use HelloWorld module block example for getting current category information.

Create a Block

<?php
namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
    protected $registry;

    public function __construct(  
        \Magento\Framework\Registry $registry,

    )
    {      
        $this->registry = $registry;

    }


    public function getCurrentCategory()
    {      
        return $this->registry->registry('current_category');
    }  

}
?>

Get product information In your phtml file

<?php
  $currentCategory = $block->getCurrentCategory();
            echo $currentCategory->getId();
            echo $currentCategory->getName();
 ?>

If you want to get in current category information in phtml you can use following code.

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

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply