How to get product category id on product detail page Magento 2
Please use below code :
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$categories = $product->getCategoryIds(); /*will return category ids array*/
foreach($categories as $category){
$cat = $objectManager->create('Magento\Catalog\Model\Category')->load($category);
echo $cat->getName();
}
?>
Try this,
Create a custom module like below code.
create a module block file to get current category name.
<?php
namespace Namespace\Modulename\Block;
class Blockname extends \Magento\Framework\View\Element\Template
{
protected $_registry;
public function __construct(
\Magento\Backend\Block\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');
}
}
?>
create a phtml file with below code
<?php if ($currentCategory = $block->getCurrentCategory()): ?>
<div class="detail-category-name">
<?php echo $currentCategory->getName(); ?>
</div>
<?php endif; ?>
call above phtml file via xml file.
<referenceContainer name="product.info.main">
<block class="Namespace\Modulename\Block\Blockname" name="product.category.name" template="Magento_Catalog::product/view/yourfilename.phtml" >
</block>
</referenceContainer>
And finally you can see category name just above product name on product detail page.