Magento 2 get product category id
Magento 2 get product category id – There can be more than one category of any product so we need to get all categories by product id. It is very simple to get product category id, you can use object manager to get product category details.
Magento 2 get product category id by Product Id | Magento2 Example
Here is an example to get the product categories by product id using object manager-
Product category details
You can get product categories details simply as below-
Magento 2 get product category id Example:
$productId = 100; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $product = $objectManager->get('Magento\Catalog\Model\Product')->load($productId); $categories = $product->getCategoryIds(); /*This will return category ids array so let us loop them*/ foreach($categories as $category){ $cat = $objectManager->create('Magento\Catalog\Model\Category')->load($category); echo $cat->getName(); echo "<br>"; echo $cat->getId(); } |
The above example will return category ids array. Using Magento\Catalog\Model\Category we can get category details such as name, id etc.
Current Product Category Details
If you want to get the current Product Category Details, You can load product from registry and get details simply as below-
Magento 2 get product category id Example:
$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(); } |
Advertisements