use Magento\Catalog\Api\CategoryRepositoryInterface; $categoryId = 1; // Retrieve the root category ID of the provided category ID $parentCategoryId = ''; try { $categoryRepository = $objectManager->create(CategoryRepositoryInterface::class); $category = $categoryRepository->get($categoryId); $parentCategory = $category->getParentCategory(); $rootCategory = $parentCategory->getRootCategory(); $parentCategoryId = $rootCategory->getId(); } catch (\Exception $e) { // Handle the exception }
use Magento\Catalog\Model\ResourceModel\Category\Collection; $collection = $objectManager->create(Collection::class); $collection->addAttributeToFilter('parent_id', 0); foreach ($collection as $category) { $rootCategory = $category->getRootCategory(); $parentCategoryId = $rootCategory->getId(); // Process the parent category ID }In both examples, the getRootCategory method is used as part of the Magento\Catalog\Model\Category class, which is part of the Magento_Catalog package library.