简体   繁体   中英

WP Query: Exclude ALL terms of a custom taxonomy

In WordPress I have a custom post type 'books' and two custom taxonomies 'genre' and 'series'. While all books have a genre, not all are part of a series. I want now to be able to query all non-series titles, ie all books w/o the series taxonomy. I hit the WordPress forums next and also googled for a solution, but only found how to exclude specific terms of a custom taxonomy but not the custom taxonomy itself and all terms that belong to it.

Of course, I could simply list all terms from 'series' in my tax query to exclude them, but if I add new terms for 'series' in the future, I have to remember to edit my query and I like to avoid it. That's why I came up with the following idea but it's not working:

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

As you can see I tried to query first all terms for 'series' and output them into a list in the style it would have to go into the tax array. The result I currently get is that all books appear when the query runs.

Can someone tell me where I went wrong? Or if you have another approach to exclude all terms of a custom taxonomy w/o manually tweaking the code every time a new term is added, I'm all ears.

You need it to be an array of terms, right now you are using an one element array, with the element being a comma separated list of your terms. Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM