Hello Magento Folks?,
How are things going on? Today in this article I will illustrate to you all How to Get Current Category in Magento 2. Don’t forget to visit our previously published blog How to set Magento 2 recently viewed products. Without further ado let’s begin today’s illustration How to Get Current Category in Magento 2 🚀
Mainly, to get current category details in Magento 2 means retrieving all the information that is present on the category page for example current category name, current category id and many other category details. Magento 2 with all the rich features includes the registry is for storing data. Therefore, we will initiate by getting the category data from the registry. Follow the below-given steps to Get current category in Magento 2.
Step 1: To get current category firstly we will need to create one block file on our custom extension
add Blockname.php in the following path
app\code\Vendor\Extension\Block\Blockname.php
now add following code
<?php namespace Vendor\Extension\Block; use Magento\Framework\View\Element\Template; class Blockname extends Template { protected $_registry; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Framework\Registry $registry, ) { $this->_registry = $registry; parent::__construct($context); } public function getCurrentCategory() { return $this->_registry->registry('current_category'); } }
Step 2: Now we will get a current category in the template phtml file
if ($currentCategory = $block->getCurrentCategory()) { echo $currentCategory->getName() . '<br />'; echo $currentCategory->getUrl() . '<br />'; }
That’s It.
Final Words:
Hopefully with the help of the above illustration all are able to get current category information in Magento 2. Also, make sure you share the blog with your Magento developer friends. If you have any queries to get current category or related to Magento 2 then comment down in the comment box below I will be happy to help you.
Happy Coding
In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…
In the world of business, understanding financial metrics is crucial for making informed decisions and…
Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…
In this era, businesses are always on the lookout for ways to engage with their…
Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…
E-commerce has transformed the way consumers shop for products and services and interact with businesses.…