0

I am trying to change an argument in the tax query in the main WP_QUERY object for creating the archive view for my the archive of my hierarchical taxonomy. My goal is to change one of the arguments in the tax query while leaving the rest intact.

I tried to get the current query, modify the tax_query array and then pass it to set.

add_action( 'pre_get_posts', 'slug_cpt_category_archives' );
function slug_cpt_category_archives( $query ) {
    if ( is_tax( 'TAXONOMY NAME') )  {
        $tax_query = $query->tax_query->queries;
        $tax_query['include_children'] = 0;
        $query->set( 'tax_query', $tax_query );
    }

}

Not only did it not produce the desired effect, of not including child terms, when I add this action:

add_action( 'wp_head', 'preh' );
function preh( ) {
    global $wp_query;

    print_r( $wp_query->tax_query  );
}

I see that there are now two tax_queries and both have [include_children] => 1

  • I don't know if it makes a difference or not, but pre_get_posts is an action, not a filter. You could try using add_action(), and remove the return $query. I don't think it will make a difference, but worth a try? – Chip Bennett Apr 20 '14 at 18:49
  • Chip- You are right, though it doesn't make a difference. I will update. – JPollock Apr 20 '14 at 19:13
2

@birgire answer is fine (+1 from me), however $query->tax_query->queries can contain more than one taxonomy, and $query->tax_query->queries[0] can be the query for another taxonomy.

So, if you want to set 'include_children' to false (note that it is a boolean argument) on the taxonomy 'TAXONOMY NAME', then you should be sure that you act on right taxonomy:

add_action( 'pre_get_posts', 'slug_cpt_category_archives' );

function slug_cpt_category_archives( $query ) {
  if ( is_tax( 'TAXONOMY NAME' ) )  {
    foreach ( $query->tax_query->queries as $i => $tax_query ) {
      if ( $tax_query['taxonomy'] === 'TAXONOMY NAME' ) {
         $query->tax_query->queries[$i]['include_children'] = false;
         // if you want to set 'include_children' to false for all
         // taxonomies than remove following return
         return;
      }
    }
  }
}
  • Thanks and upvoted for taking it further than my minimal quick-fix ;-) – birgire Apr 21 '14 at 9:09
1

Please try the following:

add_action( 'pre_get_posts', function( $query) {
        if( is_tax( 'TAXONOMY NAME') 
            && isset( $query->tax_query->queries[0]['include_children'] ) 
        ) $query->tax_query->queries[0]['include_children'] = 0;
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.