My category structure is set up like this:

  • Default Category
    • Category A
      • Category B
        • Category C
        • Category D
      • Category E
        • Category F

For each of the subcategories I'd like to retrieve the ID for the parent category directly below the default category. For example, on Category B, Category C and Category D, Category E, and Category F pages, Category A is the parent ID that I want.

I've tried every solution on this thread: How to get top parent Category from current category object?

None of these work for me on Magento

Below is the code that I have so far, but in this code the value of $parentId becomes 0 (Default Category's id).

$_category = Mage::getModel('catalog/category');
$parentId = $_category->getParentId();

if ($parentId == 3): ?>
    echo $this->getChildHtml('banner_sale_mens');
if ($parentId == 59): 
    echo $this->getChildHtml('banner_sale_womens');
  • this should work, although B returns A, C and D return B, ... – Fabian Blechschmidt Feb 12 '14 at 22:37

For every category the path is saved, so what about:

$path = explode('/', $category->getPath());
$path[1] // <--
  • I use this method, however the needed result lives in $path[2] in my own tests. [1] is the default category and [0] is always equal to a category id of 1, not sure why. – jesseconnr Feb 12 '14 at 22:39
  • because magento has a "over all" root category which is not shown, but you can see it in the database. Inside this ROOT category lives the whole category tree, so this makes absolute sense. – Fabian Blechschmidt Feb 12 '14 at 22:50
  • This doesn't work. This method is on the other forum as well, but if I try to echo this I get nothing. Perhaps this can't be done from the page template files? – kaitlynjanine Feb 14 '14 at 19:29
  • the Path is a static attribute of a category, therefore it is loaded every time. Check the data array inside of the category, there should be the path, I think it is a string of the form 1/2/3/4/5, but maybe it is already a array. check this and then use this knowledge :-) – Fabian Blechschmidt Feb 14 '14 at 19:37
  • 1
    Yeah, you need to actually load an object with data. $category = Mage::getModel('catalog/category')->load($categoryId). Then, $category->getPath() will have something like 1/3/86/302/..., where the last number is $categoryId. – musicliftsme Mar 15 '14 at 2:26

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.