首页 文章

WP查询:排除自定义分类的所有条款

提问于
浏览
0

在WordPress中,我有一个自定义的帖子类型'书籍'和两个自定义分类“流派”和“系列” . 虽然所有书籍都有类型,但并非所有书籍都是一个系列的一部分 . 我现在想要查询所有非系列 Headers ,即所有没有系列分类的书籍 . 我接下来点击了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);?>

正如您所看到的,我尝试首先查询“系列”的所有术语,并将它们输出到一个列表中,该列表必须进入税收数组 . 我目前得到的结果是查询运行时会出现所有书籍 .

谁能告诉我哪里出错了?或者,如果您有另一种方法可以排除自定义分类法的所有术语,而不是每次添加新术语时手动调整代码,我都会听到 .

1 回答

  • 0

    您需要将它作为一个术语数组,现在您正在使用一个元素数组,该元素是逗号分隔的术语列表 . 试试这个:

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

相关问题