How to Get Top Parent Category from Current Category Object in Magento 1

categorymagento-1

How can I get the top level parent category (just after Default Category) from current category object? I want the Category Name and Category URL of that parent category to show in the subcategories.

  • Default Category
    • Cat A
      • Cat B
        • Cat C

How can I get Cat A's Name and URL in Cat B and Cat C objects?

Best Answer

$category->getPath() will return the ids of all categories from the tree root to the current one separated by slash (/). Here is an example: 1/2/56/124/543. The first one is the 'root of roots'. The second one is the catalog root (default category). The rest of them are simple categories. So you can do something like this.

$path = $category->getPath();
$ids = explode('/', $path);
if (isset($ids[2])){
    $topParent = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($ids[2]);
}
else{
    $topParent = null;//it means you are in one catalog root.
}

Now you can get the name and url like this:

if ($topParent){
    $name = $topParent->getName();
    $url = $topParent->getUrl();
}