In this post I am going to explain how to get parent category 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 31 32 33 34 35 36 | 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 parent category object */ public function getParentCategory($categoryId) { return $this->getCategory($categoryId)->getParentCategory(); } /* Get parent category Id */ public function getParentId($categoryId) { return $this->getCategory($categoryId)->getParentId(); } /* Get all parent categories ids */ public function getParentIds($categoryId) { return $this->getCategory($categoryId)->getParentIds(); } |
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 26 27 | $categoryId = 10; // Load category by category ID $category = $block->getCategory($categoryId); echo "<pre>"; print_r($category->getData()); echo "</pre>"; // Get parent category object $parentCategoryObj = $block->getParentCategory($categoryId); echo "<pre>"; print_r($parentCategoryObj->getData()); echo "</pre>"; // Get parent category Id $parentCategoryId = $block->getParentId($categoryId); echo $parentCategoryId; // Get array of all parent category ids $parentIdsArray = $block->getParentIds($categoryId); echo "<pre>"; print_r($parentIdsArray); echo "</pre>"; |
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 30 31 | $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 parent category object $parentCategoryObj = $category->getParentCategory($categoryId); echo "<pre>"; print_r($parentCategoryObj->getData()); echo "</pre>"; // Get parent category Id $parentCategoryId = $category->getParentId($categoryId); echo $parentCategoryId; // Get array of all parent category ids $parentIdsArray = $category->getParentIds($categoryId); echo "<pre>"; print_r($parentIdsArray); echo "</pre>"; |
Thats it. Enjoy Magento 2!!
Leave a Reply