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();
    }
}

2 Answers 2

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;
    }
}
0

Use setPageSize to limit the categories.

$category = $this->_categoryModel->load($categoryId);
$subCategories = $category->getChildrenCategories()->setPageSize(3);

Reference Link

Note - Do not use object manager in phtml file. It's not recommended way instead create Block Class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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