Magento 2: How to Get All Parent Category IDs from Current Category ID

categorymagento2

I'm getting the current category Id using Registry like

$categoryId = $this->_registry->registry('current_category')->getId();

and to get the parent categories I tried this

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory=$objectManager>get('\Magento\Catalog\Model\CategoryFactory');
$category = $categoryFactory->create()->load($categoryId);
$parentCategories = $category->getParentCategories();

Now when Print_r() this category then it shows me memory limit but I just want to show all the Ids of the parent categories I also tried

$parentCategories = $category->getParentCategories()->getId();

but it shows me an error… how can I get only the Ids of the parent categories? Thanks in advance

Best Answer

Just iterate throu the collection (assuming you have all parent categories in the collection like you posted above - I'm not sure you will get them that way),run foreach:

foreach ($parentCategories as $cat){
  echo $cat->getId();
}

But there is a nice method in the category model called getParentIds(). That should work:

$category->getParentIds();
Related Topic