I have a hierarchical categories tree, meaning up to 3-4 subcategories with posts. When clicking on a category link in the home page, I am redirected to the category page.

I need to check if there are no subcategories for the current category, then show posts, BUT if there are subcategories, then show only subcategories titles and descriptions with no posts at all. Next, if I click on a subcategory title, check again if there are child categories to that subcategory. If there are, show the titles and descriptions; if none, show the posts related to that subcategory.

What I did so far (code added to category page):

Get the ID of the current category:

   $CategoryPar = get_category( get_query_var( 'cat' ) ); 
   $cat_id = $CategoryPar->cat_ID;

Check if the current category has children/subcategories and print them:

$args = array(
    'child_of'           => $cat_id,
    'title_li'           => __( ' ' ),
    'current_category'   => 0,
    'pad_counts'         => 0,
    'taxonomy'           => 'category'
wp_list_categories( $args );

Now I get a list of the subcategories of the current category, but I still need to prevent the posts from showing in the parent category if it has children, so I have tried wrapping the loop in a conditional statement (also in category.php):

if ( category_has_children( $cat ) == false) :
    get_template_part( 'loop' ); 

and also in functions.php I added this:

function category_has_children( $term_id ) { 
    $children = get_term_children( $term_id, "category" );
    if ( is_array( $children ) ) {
        return $children;
    } else {
        return false;

while I was posting the question I saw this link How to only show posts on last child category and it helped me solve the last piece of the puzzle .

now it can be done:)))

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.