Getting Parent Category ID of a Category ID in Magento 2
In Magento 1, retrieving the parent category ID was straightforward using the Mage::getModel('catalog/category') function to load each child category ID and access its parent ID property. However, with the shift to Magento 2, this approach may no longer work due to architectural changes.
Firstly, let’s address a common misconception about using the ObjectManager directly. While this method works for quick development tasks or debugging purposes, it’s not considered best practice in production code. The recommended approach is to use dependency injection through constructors and factory methods provided by Magento’s official APIs.
Now, onto the main question - how do you get the parent category ID of a child category?
Approach 1: Using Category Factory
The Magento\Catalog\Model\CategoryFactory class provides a convenient way to load categories. Here’s an example:
$categoryId = 10; // Replace with your desired child category ID
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->create('Magento\Catalog\Model\CategoryFactory');
$childCategory = $categoryFactory->create()->load($categoryId);
if ($childCategory->getId()) {
echo 'Parent Category ID: ' . $childCategory->getParentId(); // Outputs the parent category ID
}
Approach 2: Using Category Repository
Magento also provides a Magento\Catalog\Api\CategoryRepositoryInterface, which offers better performance and is more aligned with Magento’s service-oriented architecture.
$categoryId = 10; // Replace with your desired child category ID
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryRepository = $objectManager->create('Magento\Catalog\Api\CategoryRepositoryInterface');
$childCategory = $categoryRepository->get($categoryId);
if ($childCategory) {
echo 'Parent Category ID: ' . $childCategory->getParentId(); // Outputs the parent category ID
}
Conclusion
Both of these approaches will allow you to retrieve the parent category ID of a child category in Magento 2. However, for production code, I would recommend using the Magento\Catalog\Api\CategoryRepositoryInterface as it’s designed to be used within Magento’s service layer and offers better performance.
Remember, while this blog post provides examples using the ObjectManager for illustration purposes, in your actual development environment, you should use dependency injection through the constructor or factory methods provided by the official Magento APIs. This ensures your code is maintainable, testable, and adheres to Magento’s coding standards.
For more advanced category management functionality like getting all ancestors of a category, I recommend checking out our comprehensive guide on Category Tree Management in Magento 2.
Happy coding!