How to Get Current Category in Magento 2
If you are finding a way to get current category in magento 2 then you are in a right place. This article is all about what you are looking for.
I assume that you already have module. So, first you need to create one block file, if you already have it then use that block and paste the below code.
saveCopyzoom_out_mapnamespace Devhooks\Module\Block;
class Module extends \Magento\Framework\View\Element\Template
{
protected $registry;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
array $data = []
)
{
$this->registry = $registry;
parent::__construct($context, $data);
}
public function getCurrentCategory()
{
return $this->_registry->registry('current_category');
}
}
In above code we have used \Magento\Framework\Registry
Magento registry to get current category. Now, we'll get that on our .phtml
file.
saveCopyzoom_out_mapif ($currentProduct = $block->getCurrentCategory()) { echo $currentCategory->getName() . '<br />'; }
In above code we have echo Name
attributes but you can get it all other as well.
Finally, we are done, let's flush or refresh cache and test the result.
That’s it.
I hope this post helped you to find what you were looking for. Bookmark it for your future reference. Do comment below if you have any other questions on that.
P.S. Do share this note with your team.
Review other articles maybe it'll help you too.