Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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 );
share|improve this answer
    
So simple! Thanks. –  elclanrs Mar 7 '13 at 1:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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