Skip to content

Instantly share code, notes, and snippets.

@CodeProKid
Last active July 29, 2023 13:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CodeProKid/1d21fb7635141491c7c1facd5e99d1ad to your computer and use it in GitHub Desktop.
Save CodeProKid/1d21fb7635141491c7c1facd5e99d1ad to your computer and use it in GitHub Desktop.
Exclude child categories from a category archive page in WordPress
<?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' );
@chellestein
Copy link

God bless you, seriously. Thank you so much for this.

@RavanH
Copy link

RavanH commented Oct 10, 2022

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