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.
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.
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(); ?>
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!!
you should use
$categoryId = (int)$this->getRequest()->getParam('id', false);
and then with instantiated
\Magento\Catalog\Api\CategoryRepositoryInterface
use
$this->categoryRepository->get($categoryId);