首页 > 解决方案 > 如何查询没有两个标签的帖子?

问题描述

假设我有两个标签,red并且small. 我想获得所有不是red and small的帖子。我想包含要么是 要么 的帖子 它们不能同时是两者。red small

tag__not_in参数不起作用,因为它将排除只是red或只是small.

我也尝试了下面的税务查询,但后来意识到它与上面的相同。

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

我觉得必须有一种方法可以做到这一点,而我只是缺少一些简单的东西。那,我对逻辑反转感到困惑。有任何想法吗?

标签: wordpress

解决方案


你可以再试一次

<?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 );
?>

推荐阅读