:::: MENU ::::

Magento 2 get current category information

Magento 2 get current category information

Today we talk about how to get Magento 2 current category information like category id, category name and other 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->geId();
            echo $currentCategory->geName();
 ?>

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->geId();
    echo $currentCategory->geName();
?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: January 17, 2018


So, what do you think ?