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

时间:2015-01-21 23:59:38

标签: php arrays wordpress variables

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

正如你所看到的,我试图首先查询“系列”的所有术语,然后将它们输入到必须进入税收数组的样式的列表中。我目前得到的结果是查询运行时会出现所有书籍。

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

1 个答案:

答案 0 :(得分: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')
        ),
);
相关问题