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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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