1

I'm using pre_get_posts to filter by using $wp_query->set( 'tax_query', $tax_query );

I'm probably better-off doing this with a new WP_Query, but if someone knows something I don't I'd love to hear it

Problem, I need to set a default taxonomy & preserve the ability to show all posts.

For instance:

/cpt/?taxo=this shows all cpt's which have a taxo-term == this.

$taxo_terms = [];
if( !empty( $_GET['taxo'] ) ){
  $types = explode(',', $_GET['taxo']);
  foreach ($types as $key => $val) {
    $taxo_terms[$key] = sanitize_key($val);
  }
}
else{
    $taxo_terms[]='this'; // here's where things get ugly.
}

$tax_query = [];
if( !empty($taxo_terms) ){
  $tax_query[] = [
    'taxonomy' => 'taxo',
    'field' => 'slug',
    'terms' => $taxo_terms,
    'operator' => 'AND',
  ];
  $wp_query->set( 'tax_query', $tax_query );
}

Next, I want to add /cpt/?taxo=all to show all posts, regardless of what taxo->terms they have.

I'm hoping to find a way to unset the current tax_query from the loop, using pre_get_posts.

Is there a way to $wp_query->UNSET?

I've tried $wp_query->set( 'tax_query', null );

Next plan of attack is to work with the and/or operator, which may help.

Suggestions appreciated. Can provide more context if anyone's interested. Thanks!

edit: useful technique found here: Obliterate the main query and replace it

  • 1
    Log all of the contents of the $wp_query object inside that filter, taxonomy queries are referenced in multiple places in there. I think you have to manually unset the tax query object that gets created before the filter runs, which is separate from the tax query var that set modifies. – Milo Nov 24 '17 at 1:10
1

This fixed it! :) Hat-tip gmazzap for the useful info: Obliterate the main query and replace it

function wpse_286813_omit_all( $query_vars ){

  // triggered also in admin pages
  if ( is_admin() )
    return $query_vars;

  if( !empty($query_vars['taxo']) && $query_vars['taxo'] === 'all' ){
    $query_vars['taxo']='';
  }
  return $query_vars;

}
add_filter( 'request', 'wpse_286813_omit_all' );

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.