5

I am using Magento ver1.6.1. I need to get the root category of a store. I search in google by didn't get any good idea/code. Let me know how to get the root category of a store?

Mage::app()->getStore()->getRootCategoryId()

The above code gives the default root category, but I need the category Id which we select during store creation.

Sankar Subburaj
  • 4,992
  • 12
  • 48
  • 79

2 Answers2

14

have you tried:

Mage::app()->getStore($storeId)->getRootCategoryId();
Anton S
  • 12,750
  • 2
  • 35
  • 37
  • 3
    Note that if you are fetching store data within an install/upgrade script for an extension, you must run Mage::init() first, or the store object will not be populated. – Brandon G Mar 28 '12 at 17:42
0

Writing it for my own help as my platform was configured in multi store views and by all means I was not getting the correct root category id. I all of the below solutions:

Sol 1:

Mage::app()->getStore($storeId)->getRootCategoryId(); //The result was ID: 2

Sol 2:

Mage::app()->getStore()->getRootCategoryId(); //The result was ID: 2

Sol 3:

$store = Mage::getModel('core/store')->load(Mage_Core_Model_App::DISTRO_STORE_ID);
$categoryId = $store->getRootCategoryId();// The result was again ID: 2

The method that only worked and returned ID: 1 is given below and was taken from here

public function getRootCategoryId()
{
    $categories = Mage::getModel('catalog/category')->getCollection();
    $categIds = $categories->getAllIds();
    asort($categIds);
    foreach ($categIds as $k => $catId)
    {
        $category = Mage::getModel('catalog/category')->load($catId);
        if ($category->name)
        {
            return $catId;
        }
    }
}
Imran Zahoor
  • 2,521
  • 1
  • 28
  • 38