Reading the Current Category in Magento 2

Reading the Current Category in Magento 2

On category and product pages, Magento 2 stores the active category in its registry, so templates and blocks can read it.

From the registry

<?php

$registry = $objectManager->get('Magento\Framework\Registry');
$category = $objectManager->create('Magento\Catalog\Model\Category')->load($registry->registry('current_category')->getId());

?>

A one-line version

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

Both examples use the object manager for brevity. In real modules, inject Magento\Framework\Registry (or a layer resolver) through your class constructor instead, which is easier to test and survives upgrades better.

Want this done for you? Find out more about our Magento development service.

Keep reading

Related articles

All articles

Need a hand?

Stuck on something similar?
We can fix it with you.

Send us the problem. A senior developer reads every message and replies within one working day.