1

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?

1 Answer 1

0

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();
4
  • it is giving page not found error when I use $block... actually there is no $block variable in my .php file .... I am using file vendor/magento/module-catalog/Helper/Product/View.php
    – 1990rk4
    Commented Sep 29, 2018 at 11:12
  • bro i just gave you the logic, not a full code Commented Sep 29, 2018 at 11:35
  • are you new in magento 2 ? Commented Sep 29, 2018 at 11:36
  • yes.. i have already checked ur logic before posting this question. it will work only in .phtml files
    – 1990rk4
    Commented Sep 29, 2018 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.