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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | $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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | $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!!
Leave a Reply