Janny Bomans Janny Bomans - 7 months ago 15
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:

2
- 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

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);
unset($ids[0]);

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

Comments