WP 查询:排除自定义分类的所有术语


WP Query: Exclude ALL terms of a custom taxonomy

在WordPress中,我有一个自定义帖子类型"书籍"和两个自定义分类法"流派"和"系列"。虽然所有书籍都有一种类型,但并非所有书籍都是系列的一部分。我现在希望能够查询所有非系列标题,即没有系列分类法的所有书籍。接下来我点击了WordPress论坛,也用谷歌搜索了一个解决方案,但只找到了如何排除自定义分类法的特定术语,而不是自定义分类法本身以及属于它的所有术语。

当然,我可以简单地在我的税务查询中列出"系列"中的所有术语以排除它们,但是如果将来为"系列"添加新术语,我必须记住编辑我的查询,我喜欢避免它。这就是为什么我想出了以下想法,但它不起作用:

<?php
$terms = get_terms( 'series', $args );
$count = count( $terms );
$i = 0;
foreach ( $terms as $term ) {
    $i++;
    $term_list .= "'" . $term->slug . "'";
    if ( $count != $i ) {
        $term_list .= ', ';
    }
    else {
        $term_list .= '';
    }
}
$args = array(
    'post_type' => 'books',
    'order' => 'ASC',
    'orderby' => 'date',
    'posts_per_page' => '-1',
    'tax_query'        => array(
    array(
        'taxonomy'  => 'series',
        'terms' => array($term_list),
        'field' => 'slug',
        'operator'  => 'NOT IN')
        ),
);
query_posts($args);?>

如您所见,我尝试首先查询"系列"的所有术语,并将它们输出到必须进入税收数组的样式列表中。我目前得到的结果是,查询运行时会显示所有书籍。

有人能告诉我我哪里出错了吗?或者,如果您有另一种方法来排除自定义分类法的所有术语,而无需在每次添加新术语时手动调整代码,我都会听到。

你需要它是一个术语数组,现在你正在使用一个元素数组,元素是一个逗号分隔的术语列表。试试这个:

$terms = get_terms( 'series', $args );
$to_exclude = array();
foreach ( $terms as $term ) {
    $to_exclude[] = $term->slug;
}
$args = array(
    'post_type' => 'books',
    'order' => 'ASC',
    'orderby' => 'date',
    'posts_per_page' => '-1',
    'tax_query'        => array(
    array(
        'taxonomy'  => 'series',
        'terms' => $to_exclude,
        'field' => 'slug',
        'operator'  => 'NOT IN')
        ),
);