How To Get Current Category Name in Magento 2
Magento 2 CMS is superior to other CMSs when it comes to customization. The platform allows us to customize and develop functionalities to cater to modern business requirements. In order to do so, the developer may need to perform custom solutions as shown in this post.
For example, the store owner wants to offer discounts based on category. The store offers clothing as well as footwear but the discount is to be offered on the products from the footwear category only. To develop this functionality, one needs to get the category name of the landing page. In such a scenario, use the below solution to get current category name in Magento 2 store.
Steps to Get Current Category Name in Magento 2
- Use the below code in the CategoryBrand.php file at Vendor\Module\Block.
123456789101112131415161718192021222324<?phpnamespace Vendor\Module\Block;use Magento\Backend\Block\Template\Context;use Magento\Framework\Registry;use Magento\Framework\View\Element\Template;class CategoryBrand extends Template{protected $registry;public function __construct(Context $context, Registry $registry){$this->registry = $registry;parent::__construct($context);}public function getCurrentCategory(){return $this->registry->registry('current_category');}} - Use the below code in module_index_index.xml at Vendor/Module/view/frontend/layout.
12345678910<?xml version="1.0"?><page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column"xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"><body><referenceContainer name="content"><block class="Vendor\Module\Block\CategoryBrand" name="module_index_index"template="Vendor_Module::template_file.phtml"/></referenceContainer></body></page> - Add the below code in template_file.phtml at Vendor/Module/view/frontend/templates.
1234<?php$currentCategory = $block->getCurrentCategory();echo $currentCategory->getName() . '<br />';?>
Simply, use the getCurrentCategory() in the file, wherever you need to get current category.
That’s all!
If you have any doubts regarding this post, just mention them in the Comments section below.
I would be happy to help.
Feel free to share the solution with Magento Community via social media.
Thank You.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Get Customer by Email in Magento 2
SQL Query to Find Duplicate Increment_ID From Order Table
Next