I have found the following piece of code in the WP Knowledge Base theme in order to show subcategories of a parent category. The problem is that this only works for the first level of hierarchy, so I wanted to change the if clause in order to check if the current category has children but I have no clue how to do that, any idea?
Thanks
global $term_meta, $cat, $cat_id, $wp_query;
// Check if the current category is not a first level category
// This will happen if the current category does not have any child
// If this is the case, then we simply show all it's posts
// Instead of the nice knowledgebase type things
if ( $cat->parent != '0' ) {
You could use this simple function call which returns either TRUE
or FALSE
depending on if $children
is an empty array or not.
/**
* Check if given term has child terms
*
* @param Integer $term_id
* @param String $taxonomy
*
* @return Boolean
*/
function category_has_children( $term_id = 0, $taxonomy = 'category' ) {
$children = get_categories( array(
'child_of' => $term_id,
'taxonomy' => $taxonomy,
'hide_empty' => false,
'fields' => 'ids',
) );
return ( $children );
}
So if you’re only using the built-in post
categories you can call the function like so: category_has_children( 17 );
If you need to test a custom taxonomy it will work almost the same, you’ll just need to pass in an extra parameter ‘taxonomy-slug’: category_has_children( 7, 'my_taxonomy' );
‘
To call it in your IF statement:
if( $cat->parent != 0 && ! category_has_children( $cat->term_id ) )