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.
AI-Powered Recommended Articles
How to Get Current Product in Magento 2
Learn how to retrieve the current product in Magento 2 to dynamically display product-specific information on your website.
Magento 2 Get Product Collection By Cetegory ID
Learn how to retrieve a product collection by category ID in Magento 2 for customized product listings and filters.
Get Product Collection with a Specific Attributes in Magento 2
Learn how to retrieve product collections with specific attributes in Magento 2 using custom queries.
How to Get Product Collection in Magento 2
Learn how to get product collections in Magento 2 and filter them based on various parameters.
How to Get Salable Quantity in Magento 2
Learn how to retrieve the salable quantity of a product in Magento 2 to ensure accurate inventory tracking and display on your site.
How to Use Event in Magento 2
Learn how to use events in Magento 2 to trigger custom functionality and extend store operations.