How to Get Subcategories for Specific Parent Category in Magento 2

Viewed 1

How to Get Subcategories for Specific Parent Category in Magento 2?

1 Answers

The following example shows how to list all subcategories of a specific parent category using the parent category ID and the repository.

First of all add CategoryRepository in construct:

<?php
    protected $categoryRepository;
    
    public function __construct(
        \Magento\Catalog\Model\CategoryRepository $categoryRepository
    ) {
        $this->categoryRepository = $categoryRepository;
    }
?>

Now you can use the following way:

<?php
    $categoryId = [YOUR_CATEGORY_ID];
    $category = $this->categoryRepository->get($categoryId);
    $subCategories = $category->getChildrenCategories();
    foreach($subCategories as $subCategory) {
        echo $subCategory->getName();

        /* For Sub Categories */
        if($subcategorie->hasChildren()) {
        $childCategoryObj = $this->categoryRepository->get($subCategory->getId());
        $childSubcategories = $childCategoryObj->getChildrenCategories();
        foreach($childSubcategories as $childSubcategory) {
            echo $childSubcategory->getName();
        }
     }
    }
?>