WordPress tax_query “and” operator not functioning as desired

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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',
    ),
  ),


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x