Exclude Child Term Posts from Parent Term Archive

Okay, I’ve found an answer. Part of the issue was the missing array @goto10 mentioned, and the other part was that tax_query has required arguments. Here’s what I’m using so far:

function exclude_children($wp_query) {
    if ( isset ( $wp_query->query_vars['custom_taxomony'] ) ) {
        $wp_query->set('tax_query', array( array (
            'taxonomy' => 'custom_taxonomy',
            'field' => 'slug',
            'terms' => $wp_query->query_vars['custom_taxonomy'],
            'include_children' => false
        ) )
    }
}  
add_filter('pre_get_posts', 'exclude_children'); 

I’d prefer to be using a variable for taxonomy => custom_taxonomy rather than hard coding the value in as that seems like a more reusable solution, but I don’t know how to pull the values from the WP_Tax_Query object.

The important takeaway from this is that taxonomy, field, and terms are all required values, though that’s not clear from the Codex.

Leave a Comment