How to get product category Id on product detail page Magento 2?
-
06-04-2021 - |
Question
I have a product which have assigned into more than 5 categories. I want to show the category detail of that product on product detail page. But which category detail I need to show?
I want to show the category name of that category from where the user coming.
Can anyone suggest the solution?
La solution
You have to have created a module to show a current category on the product page. Check below files
app/code/Vendor/Module/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Vendor_Module',
__DIR__
);
app/code/Vendor/Module/etc/module.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Vendor_Module" setup_version="1.0.0">
</module>
</config>
app/code/Vendor/Module/Block/Module.php
<?php
namespace Vendor\Module\Block;
class Module extends \Magento\Framework\View\Element\Template
{
/**
* Constructor
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Registry $registry,
array $data = []
) {
$this->_registry = $registry;
parent::__construct($context, $data);
}
public function getCurrentCategory()
{
return $this->_registry->registry('current_category');
}
}
app/code/Vendor/Module/view/frontend/templates/currentCategory.phtml
<?php
/**
* @var $block \Vendor\Module\Block\Module
*/
?>
<div class="category-name">
<?php if($block->getCurrentCategory()): ?>
<h3><?= __('Category') ?>: <?= $block->getCurrentCategory()->getName();; ?></h3>
<?php endif; ?>
</div>
app/code/Vendor/Module/view/frontend/layout/catalog_product_view.xml
<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="product.info.main">
<block class="Vendor\Module\Block\Module" name="current.category.on.product" template="Vendor_Module::currentCategory.phtml" before="-"/>
</referenceContainer>
</body>
</page>
Hope this will work for you.
Autres conseils
If you want to get the current product category id then use below code
NOTE: Please do not use the Object manager
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Block\Product\View')->getProduct();
$categoryId = $product->getCategoryId();
$category = $objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
echo $cat->getName();
/*echo "<pre>";
print_r($category->getData());*/
?>
I hope this is helpful to you!!