Is removing orphaned wp_postmeta records safe?

I am using woocommerce as a shopping cart on a wordpress site.
Products and Product Variations are each stored as records in the wp_posts table.
Each of these Variations have aprox. 15-20 associated records in wp_postmeta (to store various details about that product, such as SKU or price).

What I’ve discovered is that many variations (over 600 in this case) do not have an associated parent product. Well, they do but that Parent Product no longer exists.
I have found the following to remove these orphaned variations from wp_posts:

DELETE o FROM `wp_posts` o
LEFT OUTER JOIN `wp_posts` r
ON o.post_parent = r.ID
WHERE r.id IS null AND o.post_type="product_variation"

I think this will work well for that purpose. But it would still leave many records in wp_postmeta table.

My question is, can I remove any record from wp_postmeta whose post_id does not correspond to an existing record in wp_posts.
I mean, I know I can do it, but is there any potential pitfall of removing those orphaned records from wp_postmeta.
That is, if meta info corresponds to a product variation that does not exist. can I safely delete it?

2 Answers
2

A different way of doing this (not better, but easier to follow) would be:

DELETE * FROM wp_postmeta WHERE post_id NOT IN (SELECT ID FROM wp_posts)

Obviously changing the prefixes from ‘wp_’ to whatever your setup uses

Leave a Comment