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.
Sometimes I like to see what it would look like to replace a loop with a
closure, at least as an exercise. Since I tried it with this, I’ll share:
<?php
// First, read the reads
$materials = wp_get_post_terms( get_the_ID(), ‘acme_materials’ );
$child_count = array_reduce( $materials, function( $count, $material ) {
return $count + count( get_term_children( $material->term_id,
‘acme_materials’ ) );
});
if ( $child_count > 0 ) {
// Some term has children
} else {
// No terms have children
}
That’s good stuff, Dylan. Thanks for sharing it.
Closures are fun (I use them a lot in JavaScript), but I tend to avoid them in WordPress simply because so much depends on the version of PHP on which the project is running.
Yes, don’t put that in a plugin intended to support the minimum WordPress
PHP 5.2 requirement! That’s why I do these as an exercise – for hosts I
control or in dreams of the day the minimum version rises to at least 5.3…
thanks! this will come in handy!
1-check-if-term-has-children.php:
shouldn’t this
// The term has no children
be
// The term has children
Autopilot mistake on my part. Already fixed up!
I ran into a situation where I needed something like this, my solution made it into a little bit more of a mini plugin, but it returns a list of terms within a taxonomy, and any children. May be worth taking a look at! https://gist.github.com/dsmy/0215640bf15512ce0b75
Sweet – thanks for sharing that!