Last active
July 29, 2023 13:16
-
-
Save CodeProKid/1d21fb7635141491c7c1facd5e99d1ad to your computer and use it in GitHub Desktop.
Exclude child categories from a category archive page in WordPress
This file contains hidden or 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 | |
/** | |
* Excludes child terms from the main query on the category archive. | |
* | |
* @param object $query the WP_Query instance | |
* @return void | |
* @access public | |
*/ | |
function rk_fix_tax_queries_on_archives( $query ) { | |
// Only run this on the main query for the category archive | |
if ( ! is_admin() && $query->is_category() && $query->is_main_query() ) { | |
// What category is this | |
$cat = $query->query_vars['category_name']; | |
// Build the new query args | |
$tax_query = array( | |
array( | |
'taxonomy' => 'category', | |
'field' => 'slug', | |
'terms' => $cat, | |
'include_children' => false, | |
), | |
); | |
// Set the new query args to $query->query_vars['tax_query'] | |
$query->set( 'tax_query', $tax_query ); | |
// Setting the query args is not enough, we have to create a new tax query object | |
// and force feed it to the query | |
$query->tax_query = new WP_Tax_Query( $tax_query ); | |
} | |
} | |
add_action( 'parse_tax_query', 'rk_fix_tax_queries_on_archives' ); |
God bless you, seriously. Thank you so much for this.
Maybe a bit less "force feed it to the query" with the pre_get_posts
hook...
This is an example for a custom taxonomy 'localisation' without the need to force a new WP_Tax_Query( $tax_query );
again:
function exclude_children_on_archives( $query ) {
// Only run this on the main query for a localisation term archive.
if ( ! is_admin() && $query->is_tax('localisation') && $query->is_main_query() ) {
// What term is this.
$term = $query->query_vars['localisation'];
// Build the new query args.
$tax_query = array(
array(
'taxonomy' => 'localisation',
'field' => 'slug',
'terms' => $term,
'include_children' => false
),
);
// Set the new query args to $query->query_vars['tax_query'].
$query->set( 'tax_query', $tax_query );
}
}
add_action( 'pre_get_posts', 'exclude_children_on_archives' );
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you really much, I tried everything else but this was the only code that actually worked.