How To Get Parent Category ID In Magento 2
Featured 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.