Andrii Kovalenko
Andrii Kovalenko

Reputation: 2227

How to get term by name if the term is child of another one?

I could get term by a function

get_term_by( 'name', 'Test', 'my-taxonomy' )

Taxonomy terms structure is

level 1 --> Test

level 2 --> Test

Test

How to get term if the term is child of level 1 term?

Need to get level 1 -> Test

And which term I get with my snippet?

level 1 -> Test

or level 2 -> Test

or Test?

get_term_by( 'name', 'Test', 'my-taxonomy' )

Upvotes: 0

Views: 208

Answers (1)

kaize
kaize

Reputation: 811

It's not exactly what you look for but it will guide you through

With get_term_by( 'name', 'Test', 'my-taxonomy' ) what you get is child term

That means from level 1 -> Test you get Test

If you want to get the parent term of test you can use get_term($child_term_id, 'my-taxonomy');

Your code should be like this:

$child_term = get_term_by( 'name', 'Test', 'my-taxonomy' );

$parent_term = get_term( $child_term->parent, 'my-taxonomy' );

You can var_dump $child_term & $parent_term to check the results

*You can also try with

get_term_parents_list( $child_term->term_id, 'my-taxonomy' )

Upvotes: 1

Related Questions