Through the natural course of managing a WordPress site and its database, you may end up with some orphaned post meta. This is especially true if you run any delete queries on the posts table directly in MySQL, or if you do a lot of plugin/custom code development and/or testing.
The following MySQL queries can help you check for and delete any orphaned post meta entries (i.e. those post meta entries where no post ID matches).
IMPORTANT: be sure to backup your database before running any direct MySQL queries – especially those that delete data.
Get a list of orphaned post meta
SELECT * FROM wp_postmeta pm LEFT JOIN wp_posts wp ON wp.ID = pm.post_id WHERE wp.ID IS NULL
Delete orphaned post meta
DELETE pm FROM wp_postmeta pm LEFT JOIN wp_posts wp ON wp.ID = pm.post_id WHERE wp.ID IS NULL
Leave a Reply