🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How To Get Parent Category ID In Magento 2

By Sanjay JethvaUpdated on May 22, 2025 2 min read

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:.

  1. Using  block file
  2. Using PHTML file

Methods to Get Parent Category ID in Magento 2:

1. Using Block File

<?php

namespace 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;
    }
}

?>

2. Using PHTML File

<?php

$product = $this->getCurrentProduct();

$categoryIds = $product->getCategoryIds(); //Get Current CategoryIds

foreach ($categoryIds as $categoryId){
    $category = $this->getCategory($categoryId);   // Load Category
    $parentCategories = $category->getparent_id();   // Get Parent Category Id

    echo $parentCategories. '<br />';
}

?>

That’s it.

Use any of the above methods to get parent category ID in Magento 2.

Please share the solution with the Magento community via social media.

Thank you.

Sanjay Jethva Full Image
Article bySanjay 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.