Janny Bomans Janny Bomans - 2 years ago 79
PHP Question

Magento get all parent ids

I am having some troubles getting all parent id's from a category id.
Imagine this category tree:

- 5
- 8
- 6
- 9
- 12
- 20

Now, lets say I want all parent id's of '12'. That would be 2,6,12.
I think you know what i'm doing here. I am making the 'category_ids' field for importing products.

Thanks in advance!

Answer Source

The easiest way to do so is this:

$category = Mage::getModel('catalog/category')->load($categoryId);

Each category has a field called path that contains the ids of the parents and current category.

$path = $category->getPath();

This should return something like this 1/2/6/12. All you need to do is to split this string by / and remove the first element. That one is the id for 'root of all roots'.

$ids = explode('/', $path);

Now you should have what you are looking for in $ids

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download