1
votes

I was searching a lot on this issue, but can't find anything conslusive. Maybe someone can help me here!

I have custom post type 'place' and two custom taxonomies 'place area' and 'place category'. I am building a dropdown filter by those two taxonomies. And all works great if the filter is empty and if both taxonomies are selected. But I can't figure out how to make it work if one of the taxonomies has value and another one is null.

Here's my query:

if(($category == null) && ($area == null)) {

    //Usual query without taxonomy

  } else {
    $args = array(
      'post_type'      => 'place',
      'tax_query' => array(
            array(
                'taxonomy' => 'placecat',
                'field' => 'slug',
                'terms' => $category
            ),
            array(
                'taxonomy' => 'placearea',
                'field' => 'slug',
                'terms' => $area
            )
        )
    );
  }
  $the_query = new WP_Query( $args );

I thought that the null value will mean all taxonomy terms, but it seems like it's looking for a non-existent term and returns empty result.

Any ideas how I can exclude taxonomy from query if the term value is null?

1

1 Answers

2
votes

If you check them separately you can also add them separately.

$args['post_type'] = 'place';

if ( $category != null ) {  
    $args['tax_query'][] =  array(
        'taxonomy' => 'placecat',
        'field' => 'slug',
        'terms' => $category
     );
}

if ( $area != null ) {  
    $args['tax_query'][] = array(
        'taxonomy' => 'placearea',
        'field' => 'slug',
        'terms' => $area
     );
}

In this scenario we only add them to the tax_query parameter if they are not null.