Skip to content

Instantly share code, notes, and snippets.

@ngearing
Created June 8, 2018 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngearing/bad75c78f530fa38feb0096f5207a783 to your computer and use it in GitHub Desktop.
Save ngearing/bad75c78f530fa38feb0096f5207a783 to your computer and use it in GitHub Desktop.
Exclude posts from child categories on archive pages
<?php
/**
* Filter the archive posts to only display posts of the current Term not child Terms.
*
* @param WP_Query $query The query instance.
* @return void
*/
function filter_archive_posts( $query ) {
if ( is_admin() || ! $query->is_main_query() || ! is_category() ) {
return;
}
if ( isset( $query->tax_query ) ) {
// Loop through current queries and exclude children.
$tax_query = array_map( function( $q ) {
$q['include_children'] = false;
return $q;
}, $query->tax_query->queries );
// Set query and relation.
$query->set( 'tax_query', [
'relation' => $query->tax_query->relation,
$tax_query,
] );
}
}
add_action( 'pre_get_posts', 'filter_archive_posts', 10 ,1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment