0

I have number of sub categories under main category. I have to get only four sub categories of main category. Any solution for this?

Here is the code for get sub categories:

$catId = 3; // Parent Category ID
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);
$subcats = $subcategory->getChildrenCategories();
    foreach ($subcats as $subcat) {
        echo $subcat->getName();
    }
}
1

Try Below Snippet:

$catId = 3; // Parent Category ID
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);
$cnt = 0;
$subcats = $subcategory->getChildrenCategories();
    foreach ($subcats as $subcat) {
        $cnt++;
        echo $subcat->getName();
        if($cnt == 4)
             break;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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