If you’re in the process of working with hierarchical terms, then there’s a chance that you’re eventually going to need to know if a given term is the parent to another term.

For example, let’s say that in one of your templates, you’re responsible for displaying a list of all of the terms that do not have children for one reason or another (or maybe you’re responsible for display only terms with one children or another).

Whatever the case, this is a relatively straightforward operation to do assuming that you have the term’s taxonomy readily available.

Check If Term Has Child

Let’s say that you’re working with a hierarchical taxonomy, my_acme_taxonomy, and you’re working on playing the only terms that do not have children.

In order to do this, you can use the get_term_children function with the current term and term taxonomy to determine if the current term has any children:

For example:

And then, to determine if it doesn’t have any children, simply reverse the condition:

Straightforward enough, isn’t it? In short, we’re taking a taxonomy term that we know exists and then asking if it has any children.

If it does have children, then the conditional evaluation will result to true; otherwise, we end up with a false value.

Of course, this doesn’t take into account if a term has multiple children and you’re curious if it has a particular child, but that’s a post for another day.

Share:

Leave a Reply