How to get all assigned categories of a specific product in Magento 2

If you want to ll assigned categories of a specific product by PHP on your phtml file, follow these steps:get all assigned categories of a specific product in Magento 2

1. First, define the product ID in your phtml file, like this:

$productId = 1;


2. Then, get the product by the product ID in your phtml file, like this:

$product = $block->getProductById($productId);


3. Then, get the category IDs by the product in your phtml file, like this:

$categoryIds = $product->getCategoryIds();


4. Then, get the categories by the category ID in your phtml file, like this:

$categories = $block->getCategoryCollection()
                    ->addAttributeToFilter('entity_id', $categoryIds);


5. Then, get the category names by the categories in your phtml file, like this:

foreach ($categories as $category) {
    echo $category->getName() . '<br>';
}
Now you will see assigned category names of a specific product, and output will look like this:
Men's shirt
Kid's shirt

get all assigned categories of a specific product in Magento 2expoundsofttechsolution

What is GMT?