Delete orphaned post meta in WordPress
Clean up custom-field rows left behind by deleted posts, with one SQL query and a backup first.
From the archive: first published on mohamedsharaf.net in November 2014. Rewritten and checked in 2026; some details may be out of date.
When posts are deleted outside WordPress (or by badly written plugins), their custom fields can stay behind in the wp_postmeta table, pointing at posts that no longer exist. This query removes those orphans:
DELETE pm
FROM wp_postmeta pm
LEFT JOIN wp_posts wp ON wp.ID = pm.post_id
WHERE wp.ID IS NULL;
Take a database backup first. If your tables use a different prefix than wp_, change both table names. Want to see what will go before deleting anything? Run the same query with SELECT pm.* instead of DELETE pm.