Magento 2 store owners have to deal a lot with products and categories.
In constant efforts to improve the store’s shopping experience, the admin may want to improve which categories a product is assigned to in Magento 2 store, update the categories, etc.
In order to do so, initially, one may need to get categories from a product in Magento 2. This report will further assist to update categories and products based on the business requirements.
Also read: How to Get All Categories in Magento 2 Using API?
Method to Get Categories From a Product in Magento 2:
<?php
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
protected $product;
protected $categoryCollection;
public function __construct(Product $product, CollectionFactory $categoryCollection)
{
$this->product = $product;
$this->categoryCollection = $categoryCollection;
}
public function getCategoriesName($productId)
{
$product = $this->product->load($productId);
$categoryIds = $product->getCategoryIds();
$categories = $this->categoryCollection->create()->addAttributeToSelect('*')->addAttributeToFilter('entity_id', $categoryIds);
$categoryNames = [];
foreach ($categories as $category) {
$categoryNames[] = $category->getName();
}
$categoryName = implode(',', $categoryNames);
return $categoryName;
}
That’s it.
Also, please share the post with Magento community via social media.
Thank you.