Magento 2 – How to Get Category Tree

categorycategory-listingcategory-treemagento2

I need to show category tree, just like in admin section, in my custom page. I viewed this solution in magento.stackexchange.com. It was good but limited to 2 levels of category. I need all the categories. How can it be done?

Best Answer

I searched over internet for solution to this but got nothing useful. Then I diverted my research towards Magento core where I found \Magento\Catalog\Block\Adminhtml\Category\Tree class where I found a function getTree(). Then I tried to observed it's return value in my custom template file. The effort became fruitful as I got the desired result.

I created a block file where I have injected the above class as:

<?php
namespace Vendor\Module\Block;

class CategoriesColle extends \Magento\Framework\View\Element\Template
{

    ...
    protected $adminCategoryTree;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Catalog\Helper\Category $categoryHelper
     * @param array $data
     */
    public function __construct(

       ...
        \Magento\Catalog\Block\Adminhtml\Category\Tree $adminCategoryTree

    )
    {
        ...
        $this->adminCategoryTree = $adminCategoryTree;

    }
    public function getTree()
    {
        return $this->adminCategoryTree->getTree(); 
    }
...

}

The return value of the getTree() is the desired array of the category tree which can be verified by dumping the value in template file.

Related Topic