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 are as follows:
- Using block file
- 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.