Select posts wich has no relationship in custom taxonomy

The question:

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?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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).

Method 2

The only way is to get all the terms and exclude posts which belongs to those terms

$taxonomy = 'my_tax';
$terms = get_terms( 
    $taxonomy,
    ['fields' => 'ids'] // Get only IDS
);

// Setup your query args 
$args = [
    'tax_query' => [
        [
            'taxonomy' => $taxonomy,
            'terms' => $terms,
            'operator' => 'NOT IN' // Skip posts belonging to the passed terms
        ]
    ],
    // any other args
];
$q = new WP_Query( $args );

You would want to make sure that you actually have terms and not an empty array or a WP_Error object as this might lead to unexpected output


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment