Category ID: How To Get Current Category ID in Magento 2

This article will help you to get the current category id and their names in Magento 2. When developers develop any website using Magento then Most of the time they need all category information so they can perform other operations over the objects.

Current category ID in Magento 2

So, retrieving the current category name on the category page or list and the current category name and id on the product details page using the registry helps in the development of the Magento stores.

Here, I am giving you the step-by-step guide so by following these steps you can easily get the current category details on the Magento product details page.

 

Get The Current Category ID in Magento2

Here, I will explain how we can get the category name and ID by creating a block in Magento 2.

Step 1: Create a block file on our custom extension

Now the Blockname.php we have to create in the following path

app\code\Wishusucess\CurrentCategory\Block\Categoryid.php

Now, this block class will look like below.

<?php
/**
* Author: Hemant Singh Magento 2x Developer
* Category: CurrentCategory
* Website: http://www.wishusucess.com/
*/
namespace Wishusucess\CurrentCategory\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: How To Call Block Function in Template File

Now, we have to call the block function in our template file by using the following way then only we can get the current category name and id on the category page or the product details page.

if ($currentCategory = $block->getCurrentCategory()) {
echo $currentCategory->getName() . '<br />';
echo $currentCategory->getUrl() . '<br />';
echo $currentCategory->getId() . '<br />';
}

Here, you can see we have successfully retrieved the current category name, current category URL, and current category ID on the product details page and Magento 2 category page by calling the functions.

 

Conclusion:

Getting the current category on the product detail page by using the block function is one of the best ways in Magento 2. So hopefully you will get the category name and id by using the above solution.

 

Related Post:

File Permissions: Magento 2 Ownership And File Permission At Installation

Shipping Address API: Customer Shipping Details Using API in Magento 2

 

Recommended Post:

PayPal Account: How to Create New PayPal Account, Transfer

Magento 2.4 Installation Guide: How to Install Magento 2.4.2