0

I have a page template with a custom query:

<?
$filter = explode(' ', $_GET['filter']); // "page/?filter=taxonomy+term"
$paged = get_query_var('paged') ? get_query_var('paged') : 1;

$query = new WP_Query(array(
  'post_type' => 'articles',
  'paged' => $paged,
  'tax_query' => array(
    array(
      'taxonomy' => $filter[0],
      'terms' => $filter[1],
      'field' => 'slug'
    )
   )
));

This works fine but when there are no filters I don't want to query the taxonomy, so I thought of doing this:

$query = new WP_Query(array(
  'post_type' => 'articles',
  'paged' => $paged,
));

if (! empty($filter[0])) {
  $query->set('tax_query', array(
    array(
      'taxonomy' => $filter[0],
      'terms' => $filter[1],
      'field' => 'slug'
    )
  ));
}

But it doesn't work like it did before, when there are no filters it shows nothing and when there's any filter it just shows everything. So I'm guessing the taxonomy is not getting set in the query. What am I doing wrong?

3

You can't set query parameters after the query happens, set them before you make the query-

$args = array(
    'post_type' => 'articles',
    'paged' => $paged,
);

if( some condition )
    $args['tax_query'] = array( your tax params );

$query = new WP_Query( $args );

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.