Querying two taxonomies with tax_query not woking

Question

I have a two custom taxonomies:

  • Type
  • Product

Type can be the following:

  1. Blog
  2. Case study
  3. Webinar

Subject can be:

  1. Indoor
  2. Outdoor

I have two drop down menus in WordPress backend where a user can select what type and subject they want to show from resources (my custom post type).

Say, for example, the following posts exist in resources:

  • Post 1: Tagged with type blog and subject outdoor.
  • Post 2: Tagged with type blog and subject indoor.
  • Post 3: Tagged with subject indoor.

The user can either filter by type or subject. By this I mean not both are required, only one can be selected. But, if the user does choose both a type and subject, I want it to display posts with both tags.

Current approach:

$args = array(  
  'post_type' => 'resources',
  'post_status' => 'publish',
  'posts_per_page' => 8,
  'tax_query' => array(
    'relation' => 'AND',
    array(
        'taxonomy' => 'type',
        'field'    => 'slug',
        'terms'    => $resource_type,
    ),
    array(
        'taxonomy' => 'subject',
        'field'    => 'slug',
        'terms'    => $resource_subject,
    ),
  ),
  'tax_query' => array(
    'relation' => 'OR',
    array(
        'taxonomy' => 'type',
        'field'    => 'slug',
        'terms'    => $resource_type,
    ),
    array(
        'taxonomy' => 'subject',
        'field'    => 'slug',
        'terms'    => $resource_subject,
    ),
  )

);
  • $resource_type: Is the variable holding the dropdown value for
    type.
  • $resource_subject: Is the variable holding the dropdown
    value for subject.

Current results:

  • When filtering by subject alone – it works.

  • When filtering by type alone – it works.

  • When filtering with both – it doesn’t work. I.e. I’ve filtered by type blog and subject indoor and it is showing me subject outdoor posts.

Alternatively, the following works when querying both, but does not work when only choosing one:

 $args = array(  
    'post_type' => 'resources',
    'post_status' => 'publish',
    'posts_per_page' => $card_count,
    'tax_query' => array(
      'relation' => 'AND',
      array(
          'taxonomy' => 'type',
          'field'    => 'slug',
          'terms'    => $resource_type,
      ),
      array(
          'taxonomy' => 'subject',
          'field'    => 'slug',
          'terms'    => $resource_subject,
      ),
    )

  );
0
, , Freddy 2 years 2019-10-22T02:55:18-05:00 0 Answers 82 views 0

Leave an answer

Browse
Browse