WordPress Check if Category Has Children

This bit of code allows you to check to see if the current category archive page has child categories. I needed to check this on a site where until you were viewing a category that has no children, you saw category listing pages and then when the category has no children, you see the listing of posts for that category at the end of the line.

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;


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


Post a comment
  1. Tariq Khan

    Work Perfectly!

  2. Karim

    /* * call this function instead .... * notice - no need for direct SQL query with this property of category * * $category->category_parent * */ function category_has_parent($catid){ $category = get_category($catid); if ($category->category_parent > 0){ return true; } return false; }

    • Matthew Price

      So my code checks to see if a cat_id has children. Your snippet will let you know if a cat_id has parents. They are different concepts. I would agree to just pick one column for the select so that * is not being used. Your function does not help me solve the problem i was having. I was trying to see if i was at the end of a category tree. So i need to see if the cat_id in question has any children...ie are there any categories out there that have this cat_id as a parent. Yours will tell you if the category in question has any parents. Matt

  3. Karim

    that is a horrible way to do it. 1. SELECT * = fail it's an expensive query, and you don't know what you're getting back 2. use wordpress hooks/built in functions instead of db queries

  4. Alireza

    Thanks alot... It was really helpfull..

  5. Alan Ilustrisimo

    Hey Buddy, thanks for the code, I am new to this wordpress and is still learning. You got a very nice and informational website. Thanks a lot.

Real Time Web Analytics ^