questions

How do I query posts that don’t have both of two tags?

Rate this post

Say I have two tags, red and small. I want to get all posts that are not red and small. I want to include posts that are either red or small, but they can’t be both.

The tag__not_in parameter won’t work, because it’ll exclude posts that are just red or just small.

I also tried the tax query below but then realized it’s the same as the above.

'tax_query' => array(
    'relation' => 'AND',
    array(
      'taxonomy' => 'post_tag',
      'field' => 'slug',
      'terms' => 'red',
      'operator' => 'NOT IN',
    ),
    array(
      'taxonomy' => 'post_tag',
      'field' => 'slug',
      'terms' => 'small',
      'operator' => 'NOT IN',
    ),
  )

I feel like there’s got to be a way to do this and I’m just missing something simple. That and I’m getting confused by the logic inversions. Any ideas?

 

✔️Solution:

You can try again

<?php
    $args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'tax_query' => array(
        'relation' => 'AND',
        array(
          'taxonomy' => 'post_tag',
          'field' => 'slug',
          'terms' => 'red',
        ),
        array(
          'taxonomy' => 'post_tag',
          'field' => 'slug',
          'terms' => 'small',
        ),
    )
);

$query_red_small = new WP_Query( $args );
$post_ids = wp_list_pluck( $query_red_small->posts, 'ID' );

$args = array(
    'post_type' => 'post',
    'post__not_in' => $post_ids
);
$query = new WP_Query( $args );
?>

Leave a Reply

Your email address will not be published.

Back to top button