orphan – Johan Hermansson https://johanhermansson.se Web developer who says random things Thu, 08 Dec 2022 21:03:05 +0000 sv-SE hourly 1 https://wordpress.org/?v=6.7.1 Delete orphan postmeta rows in WordPress https://johanhermansson.se/2020/08/delete-orphan-postmeta-rows-in-wordpress Tue, 18 Aug 2020 14:57:36 +0000 https://johanhermansson.se/?p=576 Running a WordPress site for a long time probably means you’ve tried out lots of different plugins handling your data. This usually means you have a lot orphans in your database. So very sad.

Delete orphan postmeta rows in Wordpress 1

Of course you want an orphan free database!

But you can easily clean up your database by running a few SQL queries.

First you should probably look if you have any orphan wp_postmeta rows in your database:

SELECT *
FROM wp_postmeta AS pm
LEFT JOIN wp_posts AS p ON p.ID = pm.post_id
WHERE p.ID IS NULL

Doing a LEFT JOIN means that SQL will look for posts, but still return a row if no parent post was found. And we only want to get post meta rows with no post parent; therefor we check where posts are NULL.

To be sure you won’t delete all your data, I strongly recommend to always backup your database and compare the row count from the above query with the total count of rows in your wp_postmeta table.

When you are sure, you can delete the rows with following query:

DELETE pm
FROM wp_postmeta AS pm
LEFT JOIN wp_posts AS p ON p.ID = pm.post_id
WHERE p.ID IS NULL

Happy orphan hunting!

Delete orphan postmeta rows in Wordpress 2
]]>