You can get the product category IDs from the product object using Magento 2.
You can retrieve all the category IDs assigned for products at any place, using the below code snippet.
You required product ID to fetch a list of category IDs assigned to the specific products.
You need to instantiate Magento\Catalog\Model\ProductCategoryList
class in your __construct()
method to get category IDs for a product.
<?php declare(strict_types=1); namespace Rbj\CategoryIds\Model; use Magento\Catalog\Model\ProductCategoryList; class CategoryIdFromProduct { public function __construct( private readonly ProductCategoryList $productCategory ) { } /** * get all the category id * * @param int $productId * @return array */ public function getCategoryIds(int $productId) { $categoryIds = $this->productCategory->getCategoryIds($productId); $category = []; if ($categoryIds) { $category = array_unique($categoryIds); } return $category; } }
Call from template file or from PHP class,
$productId = 10; //product id
echo $category = $this->getCategoryIds($productId);
Output:
Array ( [0] => 5 [1] => 12 )
Here 5 and 12 is the category id of the product with id is 10.
The result will be an array of category IDs for the products. This is the way to achieve category IDs of a product using Magento 2.