Lego2012
12/13/2016 - 3:30 PM

Check if a category has sub categories

Check if a category has sub categories

<?php
//* Do NOT include the opening php tag shown above. Copy the code shown below.

// Function to check if a category has sub categories
function category_has_children( $term_id = 0, $post_type = 'post', $taxonomy = 'category' ) {
    $children = get_categories( array( 'child_of' => $term_id, 'type' => $post_type, 'taxonomy' => $taxonomy ) );
    return ( $children );
}

// Get current category data
$current_category = get_category( get_query_var( 'cat' ) );

// Get ID of current category
$current_category_id = $current_category->cat_ID;

// If the current category archive does not have sub categories, bail.
if ( ! category_has_children( $current_category_id ) ) {
    return;
}