Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Andrew Shook
Andrew Shook
31,709 Points

$WP_Query select all post of given taxonomy, but only those post with no other taxonomies associated with it.

So, I've ran into a bit of a problem with a plugin in i'm building. I'm syncing a custom CRM with Wordpress. All has gone well with importing the data and mapping it to a custom post type, and two custom taxonomies. The problem I'm running into is with my database clean up method. The client wants the ability to select which taxonomy terms from the CRM get imported into into Wordpress. I have that all figured out too. My problem is that the client wants all post associated with old terms deleted if no other terms are associated with that post. I'm stumped as to how to go about this and my google-fu has failed me. Does anyone have any ideas? Zac Gordon, do have any thoughts or recommendations?

1 Answer

Andrew McCormick
Andrew McCormick
17,730 Points

what about using a tax_query?

something like: (from the codex

//this would return only posts that match the first query array AND the second one.  So in this case, ones that match the movie_genre "action or comedy" AND do not have an id from the second array terms.
$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'movie_genre',
            'field'    => 'slug',
            'terms'    => array( 'action', 'comedy' ),
        ),
        array(
            'taxonomy' => 'actor',
            'field'    => 'id',
            'terms'    => array( 103, 115, 206 ),
            'operator' => 'NOT IN',
        ),
    ),
);
$query = new WP_Query( $args );
Andrew Shook
Andrew Shook
31,709 Points

It's possible, but I'm worried about the performance impact of trying to "NOT IN" 20 to 30 terms.

Andrew Shook
Andrew Shook
31,709 Points

So I did end up using the Tax Query. I was afraid it would cause a performance hit, but it didn't.