How to get current category data in Magento 2
This blog post is about how to get the current category in Magento 2. Products are organized in Magento 2 and sometimes you need to know from which category you are executing PHP code. It is simple to programmatically get the current category.
Magneto 2 has the feature of the registry to store data. That is used to store data between the execution of data. Like you want to set data in the controller and use it in block or model. The registry is the best option for that. So let's start with getting the category data from the registry.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $currentCategory = $objectManager->get('Magento\Framework\Registry')->registry('current_category'); echo $currentCategory->getId(); echo $currentCategory->getName();
From the \Magento\Framework\Registry model, you can get the current category by calling the registry method with the “current_category” string as a parameter. This returns a category model if found from this you can get all other information.