WordPress Check If Current Category Has Children

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
}
?>

5 Comments

You must be logged in to post a comment.


  1. [...] found this code here, written by Matthew [...]


  2. Matthew, you are my hero! I'm using Widget Logic plugin in my WooCommerce powered catgalog and I didn't want to have the layered nav show up when a category didn't have any children categories/subcategories. Easy implementation with your code. just used "!category_has_children()" - done!


  3. Thanks that would be great. I'm going to play around with it to see if I can as well. If so, I'll post back & let you know what I came up with. It seems like there's got to be a way.
    thanks


  4. This is exactly what I'm looking for, but how could it work with custom taxonomies? Or is that even possible?

    • This code was written for wordpress 2.x and it was a long time ago. I can take a look to see if it still works and would be worth adapting to work with custom taxonomies in the next couple of days

      Matt