How to get all categories of any or current product in magento 2

Here, we will show you how to get all categories of any or current product in Magento 2. We have written code for that which are both ways i.e. Dependency Injection and Object Manager.

1. Dependency Injection

Below is a block class of our custom module (Icorethink_HelloWorld). We have injected the object of \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory, \Magento\Catalog\Model\ProductRepository and \Magento\Framework\Registry classes in the constructor of my module’s block class.

app/code/Icorethink/HelloWorld/Block/HelloWorld.php

To get the current product, we use getCurrentProduct() function. Otherwise, to get any particular product, we use getProductById($id) function.

We then fetch the category ids associated with that product. After that, we fetch the category collection data for those category ids. Here’s the code to be written in template (.phtml) file.

2. Object Manager