:::: MENU ::::
Posts tagged with: category listing

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();
?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018