How To Get Parent Category ID In Magento 2
Magento 2 is a flexible CMS that allows store owners to offer feature-rich shopping platforms and expand their E-commerce stores!
One such customization that the CMS allows is implementing category-specific features, and for that, you need the programmatic methods to get parent category ID in Magento 2.
For example, you need to display the name or image of a parent category from its subcategory. Or, impose shopping restrictions based on a particular category.
You can use the below code for such category-related customizations in Magento 2, depending on the business or client requirements.
Methods to Get Parent Category ID in Magento 2:.
Methods to Get Parent Category ID in Magento 2:
-
Using Block File
1234567891011121314151617181920212223242526272829303132333435363738394041<?phpnamespace Vendor\Extension\Block;use Magento\Framework\View\Element\Template;use Magento\Backend\Block\Template\Context;use Magento\Catalog\Model\CategoryFactory;use Magento\Framework\Registry;class CategoryBrand extends Template{protected $categoryFactory;protected $registry;protected $category;public function __construct(Context $context,CategoryFactory $categoryFactory,Registry $registry,array $data = []){$this->categoryFactory = $categoryFactory;$this->registry = $registry;parent::__construct($context, $data);}public function getCurrentProduct(){return $this->registry->registry('current_product');}public function getCategory($categoryId){$this->category = $this->categoryFactory->create();$this->category->load($categoryId);return $this->category;}}?> -
Using PHTML File
1234567891011121314<?php$product = $this->getCurrentProduct();$categoryIds = $product->getCategoryIds(); //Get Current CategoryIdsforeach ($categoryIds as $categoryId){$category = $this->getCategory($categoryId); // Load Category$parentCategories = $category->getparent_id(); // Get Parent Category Idecho $parentCategories. '<br />';}?>
That’s it.
Use any of the above methods to get parent category ID in Magento 2.
Any doubts on the topic? Feel free to share them in the Comments section below. I’d be happy to help you with the issue.
Please share the solution with the Magento community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
6 Easy Steps To Change Welcome Message In Magento 2
How To Get Access Token Of Logged In Customer In Magento 2
Next