2

How can I retrieve a list of root categories and sub categories in Magento 2?

I want to populate a drop down box with categories in admin section.

7

Try following way.


public function __construct(
        \Magento\Catalog\Helper\Category $category,
        \Magento\Catalog\Model\CategoryRepository $categoryRepository
    ) {
        $this->category = $category;
        $this->categoryRepository = $categoryRepository;
    }


$categories = $this->category->getStoreCategories();
        foreach($categories as $category) {
            echo $category->getName().'<br/>';
            $categoryObj = $this->categoryRepository->get($category->getId());
            $subcategories = $categoryObj->getChildrenCategories();
            foreach($subcategories as $subcategorie) {
                echo '    --> '.$subcategorie->getName().'<br/>';
            }
        }

1

Maybe this can help you... Get parent category, children categories & product count http://blog.chapagain.com.np/magento-2-get-parent-category-children-categories-product-count/

Not the answer you're looking for? Browse other questions tagged or ask your own question.