In this post I am going to explain how to get sub categories of specific category in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
protected $_categoryFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
array $data = []
)
{
$this->_categoryFactory = $categoryFactory;
parent::__construct($context, $data);
}
/* Get category object */
public function getCategory($categoryId)
{
$category = $this->_categoryFactory->create()->load($categoryId);
return $category;
}
/* Get all children categories IDs */
public function getAllChildren($asArray = false, $categoryId)
{
return $this->getCategory($categoryId)->getAllChildren($asArray);
}
/* Get children ids comma separated */
public function getChildren($categoryId)
{
return $this->getCategory($categoryId)->getChildren();
}Add below code snippet in template file.
$categoryId = 10; // Load category by category ID $category = $block->getCategory($categoryId); echo "<pre>"; print_r($category->getData()); echo "</pre>"; // Get comma-separated children category ids $childrenCategoryIds = $block->getChildren($categoryId); echo $childrenCategoryIds; //Get all children category ids as an array $allChildrenCategoryIdsArr = $block->getAllChildren(true, $categoryId); echo "<pre>"; print_r($allChildrenCategoryIdsArr); echo "</pre>"; //Get all children category ids ids comma-separated $allChildrenCategoryIds = $block->getAllChildren(false, $categoryId); echo $allChildrenCategoryIds;
2. Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryId = 10;
// Load category by category ID
$category = $categoryFactory->create()->load($categoryId);
echo "<pre>";
print_r($category->getData());
echo "</pre>";
// Get comma-separated children category ids
$childrenCategoryIds = $category->getChildren($categoryId);
echo $childrenCategoryIds;
//Get all children category ids as an array
$allChildrenCategoryIdsArr = $category->getAllChildren(true);
echo "<pre>";
print_r($allChildrenCategoryIdsArr);
echo "</pre>";
//Get all children category ids ids comma-separated
$allChildrenCategoryIds = $category->getAllChildren(false);
echo $allChildrenCategoryIds;Thats it. Enjoy Magento 2!!
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


Leave a Reply