I created some posts using a custom post type, then I decided to delete this custom post type but of course the old posts remained orphan inside the database.

How can I remove these orphan posts and all related attachment (post meta, etc.) safely from DB?

2 Answers 2

DELETE a,b,c 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)
WHERE a.post_type='customposttype'
  • This is not correct. If a.post_type had a value then it wouldn't be an orphan. I have a wp_postmeta table full of orphans, 2000+ and the wp_post table only has 1 post. The meta data is all for cpt which were already deleted, but these orphans gotta go too.
    – NickNo
    Mar 23, 2014 at 21:42

You need to use a few SQL queries, you can run them in something like PHPMyADMIN

DELETE FROM wp_posts WHERE `post_type` = 'customposttypename'
DELETE FROM wp_post_meta WHERE `meta_key` = 'metakeyname'

The above two will get you started. You may need to run other queries to clean up other entries but only you will know what other stuff you've inserted into your DB.

A word of warning! MAKE SURE YOU BACKUP YOUR DATABASE FIRST. And also before you run the DELETE query use a SELECT * FROM first to check whats returned and thats what you want to be deleted.

  • That second line is dangerous - it will delete all meta values regardless of the post type, which may not be what the OP wanted. You're probably better off doing something like delete from wp_postmeta where post_id in (select id from wp_posts where post_type = '[customposttype]'
    – anu
    Apr 19, 2011 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.