Magento – Magento 2 – Get Subcategories of Specific Parent Category

categorycategory-treemagento2magento2.2PHP

What I'd like to do is grab all of the child categories of a specific parent category. I'm assuming the best way to do this is by using the parent's ID and of those child categories that are returned, I'd like to grab their child categories as well.

Best Answer

Check below example to get the list of all subcategories of specific parent category using parent category ID using objectManager.

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $catId = 2;  //Parent Category ID
    $subCategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);
    $subCats = $subCategory->getChildrenCategories();
    $_helper = $this->helper('Magento\Catalog\Helper\Output');
?>
<ul class="sub-cat-ul">
    <?php
    foreach ($subCats as $subcat) {
        $_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
        $subcaturl = $subcat->getUrl();
        $_imgHtml = '';

        if ($_imgUrl = $_category->getImageUrl()) {
            $_imgHtml = '<img src="' . $_imgUrl . '" />';
            $_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, 'image');
        } ?>
        <li class="cat-li">
            <div class="cat-image">
                <a href="<?php echo $subcaturl ?>"><?php echo $_imgHtml;?></a>
            </div>
            <div class="info">
                <h4><?php echo $subcat->getName(); ?></h4>
                <a class="link" href="<?php echo $subcaturl ?>"><?php /* @escapeNotVerified */ echo __('View more') ?></a>
            </div>
        </li>
    <?php } ?>
</ul>

=====

Check below example to list of all subcategories of specific parent category using parent category ID using 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();
        }
     }
    }
?>