categories - Getting parent category hierarchy as objects from category template

admin2025-06-02  1

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.

Share Improve this question asked Feb 1, 2014 at 12:53 jbxjbx 2813 silver badges16 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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,
); 
array_push($hier,get_categories($args));
var_dump($hier);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748852870a314262.html

最新回复(0)