How to Get Categories from specific Product in Magento 2 Programmatically

To get categories from specific products in Magento 2, create the block class in your module.

Directory

app/code/VendorName/ModuleName/Block/Demo.php

Content of Demo.php

<?php
namespace VendorName\ModuleName\Block;
class Demo extends \Magento\Framework\View\Element\Template
{
protected $_categoryCollectionFactory;
protected $_productRepository;
protected $_registry;

public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
\Magento\Catalog\Model\ProductRepository $productRepository,
\Magento\Framework\Registry $registry,
array $data = []
)
{
$this->_categoryCollectionFactory = $categoryCollectionFactory;
$this->_productRepository = $productRepository;
$this->_registry = $registry;
parent::__construct($context, $data);
}

/**
* Get category collection
*
* @param bool $isActive
* @param bool|int $level
* @param bool|string $sortBy
* @param bool|int $pageSize
* @return \Magento\Catalog\Model\ResourceModel\Category\Collection or array
*/
public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
{
$collection = $this->_categoryCollectionFactory->create();
$collection->addAttributeToSelect('*');

// select only active categories
if ($isActive) {
$collection->addIsActiveFilter();
}

// select categories of certain level
if ($level) {
$collection->addLevelFilter($level);
}

// sort categories by some value
if ($sortBy) {
$collection->addOrderField($sortBy);
}

// select certain number of categories
if ($pageSize) {
$collection->setPageSize($pageSize);
}

return $collection;
}

public function getProductById($id)
{
return $this->_productRepository->getById($id);
}

public function getCurrentProduct()
{
return $this->_registry->registry('current_product');
}
}
?>

If you want to work with the current product,  the getCurrentProduct() function is used. And for the specific product use the getProductById($id) function. Add the following code in your phtml file.

$productId = 1; // YOUR PRODUCT ID
$product = $block->getProductById($productId);

// for current product
// $product = $block->getCurrentProduct();

$categoryIds = $product->getCategoryIds();

$categories = $block->getCategoryCollection()
->addAttributeToFilter('entity_id', $categoryIds);

foreach ($categories as $category) {
echo $category->getName() . '<br>';
}

 

If you want any kind of help please visit our Magento 2 Development Service and get a Quote.