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 specific products.

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

namespace Rbj\CategoryIds\Model;

use Magento\Catalog\Model\ProductCategoryList;

class CategoryIdFromProduct
     * @var ProductCategoryList
    public $productCategory;

    public function __construct(
        ProductCategoryList $productCategory
    ) {
        $this->productCategory = $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);


    [0] => 5
    [1] => 12

Here 5 and 12 is 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.