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.
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.
1 Answer
Reset to default 1I 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,
);
array_push($hier,get_categories($args));
var_dump($hier);