Home » Magento, Magento 219 September 2016

Magento 2: Get all Categories of any/current Product

This article shows how we can get list of all categories from current product or any particular product as well.

Both ways (Dependency Injection & Object Manager way) are shown below:

Using Dependency Injection (DI)

Below is a block class of my custom module (Chapagain_HelloWorld). I have injected 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/Chapagain/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.

Using Object Manager

Hope this helps. Thanks.

Magento 2

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed
  • magento

  • Kusangi Thakkar

    Hello,
    I have a doubt about how your block is loading on Magento store?
    because here you are using registry to fetch the current product,but without your block getting executed on store you cannot get that.
    so any extra configuration for that in di.xml or any other file?

  • You can use the registry code on your own block. On which file or location do you want the product data?