Choose a post without a category in wordpress

I have this script that selects a list from a specific category:

SELECT wp_posts.* 
  FROM wp_posts
       LEFT JOIN wp_term_relationships 
                 ON wp_posts.ID=wp_term_relationships.object_id 
       LEFT JOIN wp_term_taxonomy 
                 ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id 
       LEFT JOIN wp_terms 
                 ON wp_terms.term_id = wp_term_taxonomy.term_id
 WHERE wp_posts.post_type = 'post' 
   AND wp_posts.post_status = 'publish' 
   AND (
            wp_term_taxonomy.taxonomy = 'category' 
        AND wp_term_taxonomy.term_id = wp_terms.term_id 
        AND wp_terms.name = '$category' 
       )

How to choose posts that are not classified? I tried $category = ''and got 0 rows because it wp_terms.name =''has no field.

+3
source share
1 answer

You can use the sentence where id is nullto require that it left joinfail:

SELECT  p.* 
FROM    wp_posts p
LEFT JOIN 
        wp_term_relationships rel
ON      p.ID = rel.object_id 
LEFT JOIN 
        wp_term_taxonomy tax
ON      tax.term_taxonomy_id = rel.term_taxonomy_id 
        AND tax.taxonomy = 'category' 
LEFT JOIN 
        wp_terms term
ON      term.term_id = tax.term_id
WHERE   p.post_type = 'post' 
        AND p.post_status = 'publish' 
        AND term.term_id is null -- No category found
Sentence

A not existcan be performed:

SELECT  * 
FROM    wp_posts p
WHERE   p.post_type = 'post' 
        AND p.post_status = 'publish' 
        AND NOT EXISTS
        (
        SELECT  *
        FROM    wp_term_relationships rel
        JOIN    wp_term_taxonomy tax
        ON      tax.term_taxonomy_id = rel.term_taxonomy_id 
                AND tax.taxonomy = 'category' 
        JOIN    wp_terms term
        ON      term.term_id = tax.term_id
        WHERE   p.ID = rel.object_id 
        )
+2
source

All Articles