By default WordPress will list posts on each category in its hierarchy.
Example:
Parent
/- 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?
e.g.:
[grandchild categories] = array of grandchildren
if(in_array( [grandchild categories] )) : show posts
else:
do nothing
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(
array(
'include_children' => false
),
),
);
$query = new WP_Query( $args );
Or via parse_tax_query
for your category archive:
add_filter(
'parse_tax_query',
'wpse163572_do_not_include_children_in_category_archive_parse_tax_query'
);
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: http://wordpress.stackexchange.com/a/140952/22534
$query->tax_query->queries[0]['include_children'] = 0;
}
}
Note: Thanks to @PieterGoosen this is now tested and confirmed working.