get category tree in magento 2 code example

Example: magento 2 get all category tree

create this file inside magento_project pub/category_tree.php
<?php
set_time_limit(0);
ini_set('display_errors', 1);
ini_set('memory_limit','1024M');
use Magento\Framework\App\Bootstrap;
include('../app/bootstrap.php');

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager

$parentCategoryId = 2; // You have to set website root category id here



$category = $objectManager->create('Magento\Catalog\Model\Category')->load($parentCategoryId);
    
$childCategory['parent']['name'] = $category->getName();
$childCategory['parent']['id'] = $category->getId();

$childCategory['parent']["child"] = getCategory($parentCategoryId);


function getCategory($parentCatId)
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager

    $categoryRepository = $objectManager->create('Magento\Catalog\Model\CategoryRepository');
    $parentcategories = $categoryRepository->get($parentCatId);
    $categories = $parentcategories->getChildrenCategories();
    $i=0;
    $ChildCategoryValue = [];

    
    foreach($categories as $category){
        $ChildCategoryValue[$i] = ['name' => $category->getName(), 'id' => $category->getId()];
        $childCat = getCategory($category->getId());
        if($childCat){
            $ChildCategoryValue[$i]['child'] = $childCat;
        }   
        $i++;
    }

    return $ChildCategoryValue;
}

echo '<pre>';
print_r($childCategory);
echo '</pre>';

Tags:

Php Example