How would I get the top-level parent of a given term?
I am using wp_get_object_terms
to get taxonomy terms on posts, but instead of showing all tagged terms, I only want to show tagged terms’ top-level parents.
So if these are my selected terms, I only want to show Breakfast, Lunch and Dinner.
x BREAKFAST
x Cereal
x Eggs
LUNCH
Hamburger
x Pizza
DINNER
Fish
Bass
x Salmon
Trout
Lasagna
How can I do this?
Since 3.1.0,
get_ancestors()
is available. It returns an array of ancestors from lowest to highest in the hierarchy.Thanks to Ivaylo for this code, which was based on Bainternet’s answer.
The first function below,
get_term_top_most_parent
, accepts a term and taxonomy and returns the the term’s top-level parent (or the term itself, if it’s parentless); the second function (get_top_parents
) works in the loop, and, given a taxonomy, returns an HTML list of the top-level parents of a post’s terms.Once you have the function above, you can loop over the results returned by
wp_get_object_terms
and display each term’s top parent:Here is a simple function that will get you the top most parent term of any given term:
Once you have this function you can just loop over the results returned by
wp_get_object_terms
:I had the same problem and I solved easily. Check this out:
Define
$taxonomy
. It can be the slug of the taxonomy you want to get the data.After doing this, you can simply do this:
Now you got something like this:
And you can use
$parentObj
to get slug, name, id, whatever. Just by using$parentObj->slug
or$parentObj->name
as exemple.Easiest way:
Maybe this helps:
get_ancestors( $object_id, $object_type );
codex.wordpress.org
Try this!