Get Category ids from the product Magento 2.

You can get the product category ids from the product id 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 products.

You need to instantiate Magento\Catalog\Model\ProductCategoryList in your class construct() method to get category ids for a product.

call from template or PHP class,
$productId = 10;  //product id
echo $category = $this->getCategoryIds($productId);


Here 5 and 12 is category id for the product with id is 10.