I need to tell whether or not the current custom taxonomy archive page I’m viewing has child categories. I’ve got a situation where there are a lot of custom categories with children and the site is only to show posts at the end of the line. Otherwise it should show a link to the category that’s the next step down. I’ve found this snippet, but it doesn’t seem to work for custom taxonomies.
function category_has_children() {
global $wpdb;
$term = get_queried_object();
$category_children_check = $wpdb->get_results(" SELECT * FROM wp_term_taxonomy WHERE parent = '$term->term_id' ");
if ($category_children_check) {
return true;
} else {
return false;
}
}
<?php
if (!category_has_children()) {
//use whatever loop or template part here to show the posts at the end of the line
get_template_part('loop', 'index');
}
else {
// show your category index page here
}
?>
There may or may not be a better way to do this, but here’s how I would do it:
If current taxonomy term has children the
get_terms
function will return an array, otherwise it will returnfalse
.Tested and works on my local vanilla install with Custom Post Type UI plugin used for CPT generation.
There’s also a generic WP possibility to do this via get_term_children.
Assuming that you are trying to filter your terms to only show terms that either have children or not, you can actually use the
childless
parameter in yourget_terms()
function.This will output an array of terms that don’t have children.
This is by far the cleanest solution