What is the best way to get the hierarchy of parent category objects from the category.php template, when there is no post as such.

The function get_category_parents() returns a string not the objects.

The function get_categories() seems to be intended for pages where there is a post because the type argument can take either post or link.

Is there any other function I am missing? I would need something that behaves exactly like get_category_parents() but I need the category objects not just a string of all of the names.


I am not aware of a built in function that does what you are asking but it is not that hard to cook up. In fact, you are pretty close. get_categories is correct but it needs the child_of argument, which means finding the topmost parent via get_ancestors. child_of will only return children, not the specified parent, so that parent has to be inserted into the results manually.

var_dump(get_category_parents(5)); // reference
$anc = get_ancestors(5,'category');
$parent = array_pop($anc);
$hier[] = get_category($parent);
$args = array(
  'child_of' => $parent,
| improve this answer | |
  • Thanks. What I did instead is that I used the parent property of the current category. If I call get_category($current_category->parent) recursively until I find one which has parent = 0, I suppose I will get all the hierarchy. Seems to be working unless there is a catch somewhere. – jbx Feb 2 '14 at 20:38
  • @jbx: you might compare the execution time of your code to this code. I honestly don't know which will be quicker. – s_ha_dum Feb 2 '14 at 20:47
  • WHat you describe, by the way, sounds a lot like what get_ancestors already does – s_ha_dum Feb 2 '14 at 20:55

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.