Select posts wich has no relationship in custom taxonomy

I can select posts via my custom taxonomy as explained in the codex. But I am not sure, how I have to set up the tax_query if I want to get only posts which have no relation in the custom taxonomy at all. Any suggestion?

2 Answers
2

I have found an answer by myself, for those landing here by google:

$taxq = array(
    array(
        'taxonomy' => 'story_lng',
        'field'    => 'id',
        'operator' => 'NOT EXISTS',
    )
);

That results in

AND (NOT EXISTS( SELECT     
    1    
FROM    
    wp_term_relationships    
        INNER JOIN    
    wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id    
WHERE    
    wp_term_taxonomy.taxonomy = 'story_lng'    
        AND wp_term_relationships.object_id = wp_posts.ID))    
AND wp_posts.post_type="story"    
AND (wp_posts.post_status="publish"    
OR wp_posts.post_author = 1    
AND wp_posts.post_status="private")

wich is basically the same as Pieter Goosen suggested, but merged in one query (and fewer lines of code).

Leave a Comment