Magento 2 get current category
This is about how to get current category in Magento 2. Products are organized in Magento 2 and sometimes you need to know from of for which category you are executing PHP code. It is simple to programmatically get current category.
Magento 2 get current category
The following source code shows you how to create a new class that gets current category. You may add this to your module as a helper class or inject proper classes directly to needed controller or block classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php namespace MyCompany\MyModule\Helper; class MyModel extends Magento\Framework\App\Helper\AbstractHelper { protected $registry; public function __construct( ... \Magento\Framework\Registry $registry ) { ... $this->registry = $registry; } public function getCurrentCategory() { return $this->registry->registry('current_category'); } ... } |
From \Magento\Framework\Registry model you can get current category by calling registry method with “current_category” string as param. This returns a category model if found from this you can get all other information like
1 2 | $id = $category->getId(); $name = $category->getName(); |
You can use this injection method for every module class you like. Be aware, that it is only possible to get current category, if you run this code from your Magento 2 frontend. If called from command line, you won’t get a valid category object.
You can use this category object to get all related information and also to change category attributes. You may display different frontend parts based on current category. Often you need this to track user, for example if a user visits a certain category more than others. Another possibility is to check if a product is more visible in another category.
Conclusion
I showed you how to get current category programmatically in Magento 2. This is quite easy if you can inject registry model into your class. Be aware, that this only makes sense if you run this code from shop frontend. Possible classes are controller or blocks, but if you call a helper class from frontend, you may also use it as a helper method.
1 Response
[…] Magento 2 get current category by Magento2 Blog […]