2

this is my code:

    $product_id = Mage::registry('current_product')->getId();
    $product = Mage::getModel('catalog/product')->load($product_id);
    $cats = $product->getCategoryIds();
    foreach ($cats as $category_id) {
        $parentId = Mage::getModel('catalog/category')->load($category_id)->getParentId();
        $parent = Mage::getModel('catalog/category')->load($parentId);
        echo $parent->getName(); // getting the parent category, but not the base category(first level)
        $_cat = Mage::getModel('catalog/category')->load($category_id);
        echo  $_cat->getName(); // getting the category
    }

I have multiple level of categories. I want to get the first level of category using one of the subcategories id. How can i do that ?

3

Try this:

$product_id = Mage::registry('current_product')->getId();
$product = Mage::getModel('catalog/product')->load($product_id);
$cats = $product->getCategoryIds();
foreach ($cats as $category_id) {
    $category = Mage::getModel('catalog/category')->load($category_id);
    //each category has a path attribute
    $path = $category->getPath(); //should look like 1/3/14/23/55.
    //split the path by slash
    $pathParts = explode('/', $path);
    if (count($pathParts) == 3) {
        //it means the category is already a top level category
        echo $category->getName();
    }
    elseif (isset($pathParts[2])) {
        $topCategory = Mage::getModel('catalog/category')->load($pathParts[2]);
        echo $topCategory->getName();
    }
}

You can see here more details about what the category path means. (near the end).

  • I dont understand this part: isset($parts[2]. where is declared $parts ? – Attila Naghi Aug 18 '14 at 13:45
  • @Chester. Sorry. My bad. I fixed it. – Marius Aug 18 '14 at 13:55
  • but , but what will happen is current category is of level 4 ? if(count($pathParts) == 4 ) ? – Attila Naghi Aug 18 '14 at 13:58
  • If count($pathParts) == 4 then the category is of level 2 and you end up on elseif case. Where the top level category is loaded and the name is shown. – Marius Aug 18 '14 at 14:05

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.