-1

How can i get current category in magento2 ?

I want to get category name on product details page.

As using Registry is deprecated and using ObjectManager is not good practice.

3 Answers3

0

Go to your theme's form.phtml file. If form.phtml is not present in your theme copy it from Magento_Catalog module to your theme.

vendor/magento/module-catalog/view/frontend/templates/product/view/form.phtml

to

app/design/frontend/{Vendorname}/{Themename}/Magento_Catalog/templates/product/view/form.phtml

Paste the code below

<?php echo $block->getProduct()->getCategory()->getName(); ?>
Milan Chandro
  • 2,342
  • 1
  • 18
  • 25
0

To get the current category:

use block class: Magento\Catalog\Block\Category\View

Get product using: $block->getCurrentCategory() in your phtml or use the class and get in the block file.

Hope it Helps.Happy coding!!

Vijay R
  • 160
  • 4
0

you should use

$categoryId = (int)$this->getRequest()->getParam('id', false);

and then with instantiated

\Magento\Catalog\Api\CategoryRepositoryInterface use

$this->categoryRepository->get($categoryId);
Jeyaram
  • 19
  • 5