create custom block in your custom module
Vendor\Module\Block\Yourblock.php
<?php
namespace Vendor\Module\Block;
class Yourblock extends \Magento\Framework\View\Element\Template
{
protected $_registry;
protected $_categoryModel;
public $_categoryNames = array();
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Catalog\Model\Category $categoryModel,
array $data = []
)
{
$this->_registry = $registry;
$this->_categoryModel = $categoryModel;
parent::__construct($context, $data);
}
public function getCurrentProduct() {
return $this->_registry->registry('current_product');
}
protected function getCurrentProductCategories() {
$currentProduct = $this->getCurrentProduct(); // Your current product object
$categories = $currentProduct->getCategoryIds(); /*returns category ids array assigned to product*/
foreach($categories as $category):
$cat = $this->_categoryModel->load($category);
$this->_categoryNames[] = $cat->getName();
endforeach;
return $this->_categoryNames;
}
}
Vendor\Module\view\frontend\templates\category_name.phtml
<?php
$currentCategories = $block->getCurrentProductCategories();
if ($currentCategories):
foreach($currentCategories as $key => $categoryName):
?>
<div class="your-html-data">
<?php echo $categoryName; ?>
</div>
<?php
endforeach;
endif;
?>
Vendor\Module\view\frontend\layout\catalog_product_view.xml
<referenceContainer name="content">
<block class="Vendor\Module\Block\Yourblock" name="product_category_name" template="Vendor_Module::category_name.phtml" >
</block>
</referenceContainer>
I hope it will work for you.