Magento – How to get product parent category id and category id separatly in magento 2.2.6 using product ID

catalogcategory-productsmagento2.2.6productproduct-attribute

Problem definition:

I have product under below category:

Beauty --> Sun --> my-some-product-name.

where 'Beauty' is root category and 'Sun' is the subcategory of 'Beauty'.

Currently, I am trying to get root category id and subcategory id of product separately.

How to get above data in Magento 2.2.6 product ID?

Best Answer

Solution 1

<?php 
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$categories = $product->getCategoryIds(); /*will return category ids array*/
foreach($categories as $category){
    $cat = $objectManager->create('Magento\Catalog\Model\Category')->load($category);
    echo $cat->getName();
    }

?>

Solution 2

First get Category using product - and based on category you will get parent category.

$productId = 1; // YOUR PRODUCT ID
$product = $block->getProductById($productId);

// for current product
// $product = $block->getCurrentProduct();

$categoryId = $product->getCategoryIds();

// Load category by category ID
$category = $block->getCategory($categoryId);

// Get array parent categories of loaded category
$parentCategories = $category->getParentCategories();