1

I need to take the main category . i try the following code

$product = $objectManager->create('Magento\Catalog\Model\Product')->load($itemid);
$cats = $product->getCategoryIds();
print_r($cats) // It returns  more than 1 category id
foreach ($cats as $category_id) 
{                   
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    echo "<br/>categoryid". $category_id;
    $collection = $this->_categoryFactory->create()->load($category_id);
    echo "</br> Category Name ". $collection->getName();            
    echo "<br/> Parent category name" . $collection->getParentCategory()->getName();                            

}

I have a doubt which one is the main category of the product ... I am not have much knowledge in ecommerce. I am struggle which one i need to choose.

3
  • what do you mean by main category? there is no option of main category select in product Commented Nov 24, 2018 at 6:06
  • @Jigs , i want to know which one the exact category of that product. I got more than one category . for the single product Commented Nov 24, 2018 at 6:09
  • @JigsParmar , i ask about level of category how to get the category level . Top most and inner category . I need inner category Commented Nov 24, 2018 at 6:36

1 Answer 1

1

Try below code to get category level.

$product = $objectManager->create('Magento\Catalog\Model\Product')->load($itemid);
$cats = $product->getCategoryIds();
$level = 1;
foreach ($cats as $category_id) 
{                   
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    echo "<br/>categoryid". $category_id;
    $collection = $this->_categoryFactory->create()->load($category_id);
    echo "</br> Category Name ". $collection->getName();            
    echo "<br/> Parent category name" . $collection->getParentCategory()->getName();
    echo "<br/> Category level" . $collection->getLevel();
    $categoryName = $collection->getName();
    if($collection->getLevel() > $level) {
        $level = $collection->getLevel();
        $categoryName = $collection->getName();
    }                             

}
echo $categoryName; exit; // this will be the inner category name

Let me know if you need further help.

1
  • welcome @SammuSundar Happy Coding :) Commented Nov 26, 2018 at 5:52

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.