Blog

How to get Current Category details in Magento 2?

Let’s understand how to get the current category details in Magento2.

Current Category collection can be found if you are in category page otherwise you can’t get current category collection using Registry.

There are 2 steps for this:

  1. Create Block file (in New module or existing module depending on your need)
  2. Create Template file calling the Block function

Step 1: – Create Block file

Refer below code snippet for getting current category collection in Magento 2,

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
namespace Thecoachsmb\Category\Block;
class CurrentCategory extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Registry $registry,
array $data = []
) {
$this->registry = $registry;
parent::__construct($context, $data);
}
/* $categoryId as category id */
public function getCategory(){
try {
return $this->registry->registry(‘current_category’);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
return [‘response’ => ‘Category Not Found’];
}
}
}

 

Step 2 :- Create Template file

Call From template file,

If you are in category page, you got Current category details by above code snippet.

This is super easy. Hope this helps you.

Do comment below mentioning the feedback.

Happy Learning !!

Thank You !!

Leave a Reply

Your email address will not be published. Required fields are marked *