If having an issue in getting parents and children categories from a category in Magento 2 then no need to worry about this.
We’ll explore here how to get parent and child categories in Magento 2 for a specific category using simple and effective methods.
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of Object Manager
$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');// Instance of Category Model
$categoryId = 15; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);
// Parent Categories
$parentCategories = $category->getParentCategories();
// Children Categories
$childrenCategories = $category->getChildrenCategories();
?>
Hope this blog will help you.
4 comments
If you are using anywhere else then let us know.
You can use the setPageSize() function for the getChildrenCategories function because it returns the collection of the children categories.
But getParentCategories function returns the array of the parent categories for the same you have to manage manually.