In this post I am going to explain how to get parent category of specific category in magento 2.
1. Using Dependency Injection
Add below code snippet in Block class.
protected $_categoryFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
array $data = []
)
{
$this->_categoryFactory = $categoryFactory;
parent::__construct($context, $data);
}
/* Get category object */
public function getCategory($categoryId)
{
$category = $this->_categoryFactory->create()->load($categoryId);
return $category;
}
/* Get parent category object */
public function getParentCategory($categoryId)
{
return $this->getCategory($categoryId)->getParentCategory();
}
/* Get parent category Id */
public function getParentId($categoryId)
{
return $this->getCategory($categoryId)->getParentId();
}
/* Get all parent categories ids */
public function getParentIds($categoryId)
{
return $this->getCategory($categoryId)->getParentIds();
}Add below code snippet in template file.
$categoryId = 10; // Load category by category ID $category = $block->getCategory($categoryId); echo "<pre>"; print_r($category->getData()); echo "</pre>"; // Get parent category object $parentCategoryObj = $block->getParentCategory($categoryId); echo "<pre>"; print_r($parentCategoryObj->getData()); echo "</pre>"; // Get parent category Id $parentCategoryId = $block->getParentId($categoryId); echo $parentCategoryId; // Get array of all parent category ids $parentIdsArray = $block->getParentIds($categoryId); echo "<pre>"; print_r($parentIdsArray); echo "</pre>";
2. Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryId = 10;
// Load category by category ID
$category = $categoryFactory->create()->load($categoryId);
echo "<pre>";
print_r($category->getData());
echo "</pre>";
// Get parent category object
$parentCategoryObj = $category->getParentCategory($categoryId);
echo "<pre>";
print_r($parentCategoryObj->getData());
echo "</pre>";
// Get parent category Id
$parentCategoryId = $category->getParentId($categoryId);
echo $parentCategoryId;
// Get array of all parent category ids
$parentIdsArray = $category->getParentIds($categoryId);
echo "<pre>";
print_r($parentIdsArray);
echo "</pre>";Thats it. Enjoy Magento 2!!
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


Leave a Reply