7

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, or some other solution to achieve this?

10

not tested but give this a shot

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

OR

'tax_query' => array(
   'relation' => 'AND',
    array(
      'taxonomy' => 'image_tag',
      'field'    => 'term_id',
      'terms'    => array(25,41),
      'operator' => 'IN',
    ),
  ),
  • 3
    Thanks for your time! For anyone else who may find this, the first solution is the correct one. – dkeeling Aug 26 '16 at 19:01

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.