SQL query select and delete all posts from specific term

With this SQL query you can select all the posts from a specific term (and post type):

SELECT * FROM wp_posts p 
LEFT OUTER JOIN wp_term_relationships r ON r.object_id = p.ID 
LEFT OUTER JOIN wp_term_taxonomy x ON x.term_taxonomy_id = r.term_taxonomy_id 
LEFT OUTER JOIN wp_terms t ON t.term_id = x.term_id 
WHERE p.post_status = 'publish' AND p.post_type = 'post' AND t.slug = 'term-slug'

With this query you can delete all these posts:

DELETE a,b,c,d
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 e.term_id = <term id>

I'm Robbert Vermeulen. I document everything I learn and help thousands of people with coding WordPress. My site has no ads or sponsors. If you enjoy my content, please consider supporting what I do.


    No comments yet..

Leave a reply

Feel free to ask questions or make comments.