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.

  • what do you mean by main category? there is no option of main category select in product – Jigs Parmar Nov 24 '18 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 – Sammu Sundar Nov 24 '18 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 – Sammu Sundar Nov 24 '18 at 6:36
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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