dkeeling
dkeeling

Reputation: 193

Wordpress tax_query "and" operator not functioning as expected

I have a custom post type of image with a custom taxonomy called image_tag (it's hierarchical like categories). Here are some examples of the tags that might be used:

Structure (id: 25)
- House (id: 56)
- Skyscraper
Nature
- Animal
- Plant (id: 41)

So, I want to drill down through the images by selecting multiple tags in conjunction with the "and" operator. For example, finding all photos with plants and houses.

$query_args = array(
  'post_type' => 'image',
  'tax_query' => array(
    array(
      'taxonomy' => 'image_tag',
      'terms' => array(41, 56),    // IDs of "plant" and "house"
      'operator' => 'and',
    ),
  ),
);

That works fine, the problem begins when I try to include the parent terms, for example:

$query_args = array(
  'post_type' => 'image',
  'tax_query' => array(
    array(
      'taxonomy' => 'image_tag',
      'terms' => array(25, 41),    // IDs of "structure" and "plant"
      'operator' => 'and',
    ),
  ),
);

Then I get no results. I'm guessing that because I'm using the "and" operator, Wordpress doesn't include the children of the "Structure" term. Does anyone have an idea how I can get this to work?

Upvotes: 2

Views: 6192

Answers (3)

Hubert Popp
Hubert Popp

Reputation: 126

So it should look like this:

'relation' => 'AND',
   array(
         'taxonomy' => 'image_tag',
          'field'    => 'term_id',
          'terms'    => array( 25 ),
         ),
         array(
         'taxonomy' => 'image_tag',
          'field'    => 'term_id',
          'terms'    => array( 41 ),
          ),
        ),

Upvotes: 3

Hubert Popp
Hubert Popp

Reputation: 126

$query_args = array(
 'post_type' => 'image',
 'tax_query' => array(
    'relation' => 'AND',
       array(
      'taxonomy' => 'image_tag',
      'field'    => 'term_id',
      'terms' => array(25, 41),    // IDs of "structure" and "plant"
      'operator' => 'in'
      ),
    ),
  );

I had a similar problem, give this a try!

Upvotes: 0

Mo'men Mohamed
Mo'men Mohamed

Reputation: 1909

Update: You forget to close 'terms' and 'operator' by ' like this

$query_args = array(
  'post_type' => 'image',
  'tax_query' => array(
    array(
      'taxonomy' => 'image_tag',
      'field'    => 'term_id',
      'terms' => array(25, 41),    // IDs of "structure" and "plant"
      'operator' => 'in'
    ),
  ),
);

Upvotes: 0

Related Questions