Skip to content

Instantly share code, notes, and snippets.

@saas786
Forked from mikaelz/delete-orphan.sql
Created April 16, 2021 10:40
Show Gist options
  • Save saas786/bb2c733cb9a6a7a04132a85bb38188db to your computer and use it in GitHub Desktop.
Save saas786/bb2c733cb9a6a7a04132a85bb38188db to your computer and use it in GitHub Desktop.
Delete orphan postmeta and attachment in WordPress database
-- Delete orphan postmeta
DELETE pm
FROM wp_postmeta pm
LEFT JOIN wp_posts p ON pm.post_id = p.ID
WHERE p.ID IS NULL
;
-- Delete orphan attachment
DELETE p1
FROM wp_posts p1
LEFT JOIN wp_posts p2 ON p1.post_parent = p2.ID
WHERE p1.post_parent > 0 AND p1.post_type = 'attachment' AND p2.ID IS NULL
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment