Magento, Magento 2

How to Get Category Tree in Magento 2

How to Get Category Tree in Magento 2

In this tutorial, Today I will explain to how to get category tree in Magento 2. Magento 2 Category Trees structure indicates about category parent and sub categories.

If you want to get category and subcategories by category id in Magento 2, Then you can also use this article. So, Let’s start to follow the steps :

You may also like this :

Step to Get Category Tree in Magento 2 :

For that, we need to use \Magento\Catalog\Api\CategoryManagementInterface interface in our module and need to use getTree()  Method 

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * Created By : Rohan Hapani
 */
namespace RH\CustomCategory\Block;

class CategoryTree
{
    /**
     * @var \Magento\Catalog\Api\CategoryManagementInterface
     */
    private $categoryManagement;

    /**
     * @param \Magento\Catalog\Api\CategoryManagementInterface $categoryManagement
     */
    public function __construct(
        \Magento\Catalog\Api\CategoryManagementInterface $categoryManagement
    ) {
        $this->categoryManagement = $categoryManagement;
    }

    /**
     * Fetch Category Tree by Category ID
     */
    public function getCategoryTree()
    {
        $rootCategoryId = 2;
        try {
            $categoryTree = $this->categoryManagement->getTree($rootCategoryId);
            $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/Rohan.log');
            $logger = new \Zend\Log\Logger();
            $logger->addWriter($writer);
            $logger->info(print_r($categoryTree->debug(),true)); // Here, You will get category tree array object in log file.
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }
}

You can see here, We need to pass root category ID into getTree() Method. If you want to get subcategories with specific depth level then, you can use this below line in your code in getCategoryTree() function :

$rootCategoryId = 2;
$depthLevel = 2;
try {
    $categoryTree = $this->categoryManagement->getTree($rootCategoryId, $depthLevel);
    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/Rohan.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);
    $logger->info(print_r($categoryTree->debug(),true)); // Here, You will get category tree array object in log file.
} catch (\Exception $exception) {
    throw new \Exception($exception->getMessage());
}

As you can see, Here we pass 2 arguements. 1st arguement as root category ID and 2nd arguement as depth level of category.

That’s it !!!

I hope this blog will helpful for easily understand about how to get category tree in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

 

Tagged ,