Magento 2 Get categories on Product

Magento 2 Get categories on Product detail page

By on May 31, 2017

Often we need to get category information on product detail page in Magento 2. There are several options to do it. Like Dependency Injection, PHTML integration or Object Manager and straightforward API (quickest only give Category IDs).

1- Dependency Injection and Block

Create a small module to implement it. In Magento 2 modules resides in
and inside it create directories named
Block, Controller, etc and view(if required). Now let’s create a file inside etc directory named module.xml and Declare our module with version.

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
  <module name="<Vendor>_<ModuleName>" setup_version="1.0.0" />

Now we need to register with Magento ComponentRegistrar class, Let’s do that by creating file in module root i.e  app/code/<Vendor>/<ModuleName> directory named registration.php


Our module is now available for install and activate. We can achieve it by running commands

php bin/magento module:enable <Vendor>_<ModuleName>

php bin/magento setup:upgrade

Let’s move to create our interfaces, create our block file category.php in Block/Product/View

namespace <Vendor>\<ModuleName>\Block\Product/View;
use Magento\Catalog\Model\ProductRepository;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
class <ModuleName> extends \Magento\Framework\View\Element\Template
    * Core registry
    * @var \Magento\Framework\Registry
    protected $_coreRegistry = null;

    protected $_categoryCollectionFactory;
    protected $_productRepository;
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        \Magento\Framework\Registry $registry,
        array $data = []
            $this->_categoryCollectionFactory = $categoryCollectionFactory;
            $this->_productRepository = $productRepository;
            $this->_coreRegistry = $context->getRegistry();
            parent::__construct($context, $data);
     * Get category collection
     * @param bool $isActive
     * @param bool|int $level
     * @param bool|string $sortBy
     * @param bool|int $pageSize
     * @return \Magento\Catalog\Model\ResourceModel\Category\Collection or array
    public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
        $collection = $this->_categoryCollectionFactory->create();
        // select only active categories
        if ($isActive) {
        // select categories of certain level
        if ($level) {
        // sort categories by some value
        if ($sortBy) {
        // select certain number of categories
        if ($pageSize) {
        return $collection;

Ok, our block is ready, we need to setup out frontend layout and phtml files. So let’s create 2 directories frontend/layout and frontend/templates in our view directory. Layout directory will contain XML file with layout injection whereas Templates contains phtml files.

Now it’s time to create a layout file and inject out phtml into that, create a file named catalog_product_view.xml in layout. As we want our result to be shown on product detail page so we get catalog_product_view and extend it.

<?xml version="1.0"?>
<page xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <referenceContainer name="">
   <block class="<Vendor>\<ModuleName>\Block\Product\View\Category" name="product.view.category" as="product_category_data" template="<Vendor>_<NoduleName>::product/view/category.phtml">

Now create phtml file in template directory named as category.phtml

$categoryIds = $_product->getCategoryIds();

$categories = $block->getCategoryCollection()
                    ->addAttributeToFilter('entity_id', $categoryIds);
foreach ($categories as $category) {
    echo $category->getName() . '<br>';

Clear magento cache and you will see the categories name on product detail page.



Akhilesh Singh Shrinet
New Delhi, India

My Passion is to create such thing which works automatically. Coding such stuffs is my passion. I always try to learn new things, though my studies are not related to my work but I love it. I learn every things through Google(Thanks to it). As Full Stack Developer I have extensive knowledge of Laravel, AngularJs, Magento, Node.Js, React.Js, Sass/Less