1

How do you get the ID of the parent term of the current child term assigned to a post. For a custom taxonomy?

Custom taxonomy: "location"

Countries

  • Japan
  • USA
  • Mexico

Cities

  • New York
  • Austin

Say we are on a post assigned to "Japan" how do I get the ID of the parent called "Countries"? For this case it doesn't matter if it takes the highest parent or just the direct parent.

I found this:

$term_id = 21;

$child_term = get_term( $term_id, 'location' );
$parent_term = get_term( $child_term->parent, 'location' );

But it doesn't work.

0

If you just need IDs, get_ancestors will return an array of parents for any type of object:

$term_id = 21;
$ancestors = get_ancestors( $term_id, 'location' );
  • Will it return more than one parent if the structure is nested deeper? How do I just get the single ID of the parent directly above the child term? – coder May 20 '16 at 5:29
  • Check the function name it says "ancestors" which mean all parents. To get immediate parent use $immediate_parent = array_shift($ancestors); – Sumit May 20 '16 at 5:49
  • thanks champ, figured they could work that out for themselves, but there you go! – Milo May 20 '16 at 6:27

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.