Created
June 8, 2018 04:31
-
-
Save ngearing/bad75c78f530fa38feb0096f5207a783 to your computer and use it in GitHub Desktop.
Exclude posts from child categories on archive pages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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