How to only show posts on last child category

By default WordPress will list posts on each category in its hierarchy.



/- child

/– grandchild

When viewing the “Parent” category you will see a list of posts from child, grandchild and parent – even if the post is just ticked in “Grandchild”.

My question is: How do I only show posts when viewing the last child? Is there a built in WordPress function for this?


[grandchild categories] = array of grandchildren

if(in_array( [grandchild categories] )) : show posts


do nothing

Solutions Collecting From Web of "How to only show posts on last child category"

There is of course the include_children parameter for WP_Query as part of the taxonomy parameters. Which I suppose should work like this for you:

$args = array(
    'tax_query' => array(
            'include_children' => false
$query = new WP_Query( $args );

Or via parse_tax_query for your category archive:

function wpse163572_do_not_include_children_in_category_archive_parse_tax_query( $query ) {
    if ( 
        ! is_admin() 
        && $query->is_main_query()
        && $query->is_category()
    ) {
        // as seen here:
        $query->tax_query->queries[0]['include_children'] = 0;

Note: Thanks to @PieterGoosen this is now tested and confirmed working.

Those of us who have developed static websites with pages will understand the problem as Pieter has outlined in the comments above.

Essentially if one could create a page and list content on that page one has the desired effect but it is useful to use the category system in wp to manage content and order it.

Here is what I’ve done and have working:

I wrote a small function around “get_term_children” – a wordpress function.

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

Then on my category page before the loop I check if the “category_has_children”:

<?php if( category_has_children( $cat ) == false) : ?>

show posts as this is the last child category.

<? endif; ?>