How do I modify the following query to delete all posts with the custom post type “listings” that are NOT IN specific WordPress categories?
Note, I must use $wpdb->query()
in my particular situation.
My categories for exclusion are term ID’s 21, 22, and 24.
$wpdb->query('DELETE FROM wp_posts WHERE post_type = "listings"');
UPDATE – THIS query brings me a lot closer to what I am after but throws a SQL error.
DELETE FROM wp_posts a LEFT JOIN wp_term_relationships b ON ( a.ID = b.object_id ) LEFT JOIN wp_postmeta c ON ( a.ID = c.post_id ) LEFT JOIN wp_term_taxonomy d ON ( d.term_taxonomy_id = b.term_taxonomy_id ) LEFT JOIN wp_terms e ON ( e.term_id = d.term_id ) WHERE a.post_type = "listings" AND e.term_id NOT IN (21,22,24);
Error:
WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id' at line 1 for query DELETE FROM wp_posts LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_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 = "listings" AND wp_terms.term_id NOT IN (21,22,24)
Advertisement
Answer
$wpdb->query('DELETE wp_posts FROM wp_posts INNER JOIN wp_term_relationships ON wp_posts.id = wp_term_relationships.object_id INNER JOIN wp_term_taxonomy ON wp_term_relationships.object_id = wp_term_taxonomy.term_taxonomy_id WHERE wp_posts.post_type = "listings" AND wp_term_taxonomy.taxonomy NOT IN (taxonomy_1_slug, taxonomy_2_slug, etc.)');