How to Get Categories From a Product in Magento 2
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?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; } |
Any doubts in the above solution?
If so, do mention them in the Comments section below.
I’d be glad to help you out.
Also, please share the post with Magento Community via social media.
Thank you.
Jignesh Parmar
An expert in his field, Jignesh is the team leader at Meetanshi and a certified Magento developer. His passion for Magento has inspired others in the team too. Apart from work, he is a cricket lover.
Prev
How to Install Elasticsearch on Google Cloud
How to Show Address Fields in Registration Form in Magento 2
Next