There is a build in function for this already, no need to create a custom function for this. The function is called get_term_children()
and will return either
An array of child terms if the given term have children
An empty array if no child terms are found
WP_Error
object if the taxonomy does not exist
With this in mind, wrap get_term_children()
in a function and return true or false depending on the returned value if you just need a boolean value ( like a conditional tag )
function has_term_have_children( $term_id = '', $taxonomy = 'category' )
{
// Check if we have a term value, if not, return false
if ( !$term_id )
return false;
// Get term children
$term_children = get_term_children( filter_var( $term_id, FILTER_VALIDATE_INT ), filter_var( $taxonomy, FILTER_SANITIZE_STRING ) );
// Return false if we have an empty array or WP_Error object
if ( empty( $term_children ) || is_wp_error( $term_children ) )
return false;
return true;
}
You can simply now just pass the term id to the function and the correct taxonomy name if the taxonomy is anything other than category
, and you will get a boolen value back just as the build in conditional tags, true on success if the term have children, false if it does not.
if ( has_term_have_children( 21 ) ) {
// Do something if term 21 have children
}