magento 2 get all category tree

Solutions on MaxInterview for magento 2 get all category tree by the best coders in the world

showing results for - "magento 2 get all category tree"
Sara
17 Jul 2019
1create this file inside magento_project pub/category_tree.php
2<?php
3set_time_limit(0);
4ini_set('display_errors', 1);
5ini_set('memory_limit','1024M');
6use Magento\Framework\App\Bootstrap;
7include('../app/bootstrap.php');
8
9$bootstrap = Bootstrap::create(BP, $_SERVER);
10
11$objectManager = $bootstrap->getObjectManager();
12
13$state = $objectManager->get('Magento\Framework\App\State');
14$state->setAreaCode('frontend');
15
16$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
17
18$parentCategoryId = 2; // You have to set website root category id here
19
20
21
22$category = $objectManager->create('Magento\Catalog\Model\Category')->load($parentCategoryId);
23    
24$childCategory['parent']['name'] = $category->getName();
25$childCategory['parent']['id'] = $category->getId();
26
27$childCategory['parent']["child"] = getCategory($parentCategoryId);
28
29
30function getCategory($parentCatId)
31{
32    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
33
34    $categoryRepository = $objectManager->create('Magento\Catalog\Model\CategoryRepository');
35    $parentcategories = $categoryRepository->get($parentCatId);
36    $categories = $parentcategories->getChildrenCategories();
37    $i=0;
38    $ChildCategoryValue = [];
39
40    
41    foreach($categories as $category){
42        $ChildCategoryValue[$i] = ['name' => $category->getName(), 'id' => $category->getId()];
43        $childCat = getCategory($category->getId());
44        if($childCat){
45            $ChildCategoryValue[$i]['child'] = $childCat;
46        }   
47        $i++;
48    }
49
50    return $ChildCategoryValue;
51}
52
53echo '<pre>';
54print_r($childCategory);
55echo '</pre>';
56
57