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
1. Use the below code in the CategoryBrand.php file at Vendor\Module\Block.
<?php namespace 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'); } }
2. Use the below code in module_index_index.xml at Vendor/Module/view/frontend/layout.
<?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>
3. Add the below code in template_file.phtml at Vendor/Module/view/frontend/templates.
<?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!
Feel free to share the solution with Magento Community via social media.
Thank You.