Skip to content

Instantly share code, notes, and snippets.

@bookchiq
Created April 14, 2020 14:53
Show Gist options
  • Select an option

  • Save bookchiq/d33598bbf907f228632334eff8f2dca3 to your computer and use it in GitHub Desktop.

Select an option

Save bookchiq/d33598bbf907f228632334eff8f2dca3 to your computer and use it in GitHub Desktop.
Delete duplicate WordPress posts (where duplication is determined by a post meta value) and subsequently orphaned post meta
DELETE FROM wp_posts WHERE ID IN (
SELECT post_id
FROM wp_postmeta
INNER JOIN (
SELECT meta_value
FROM wp_postmeta
WHERE meta_key = 'meta_key_name'
GROUP BY meta_value
HAVING COUNT( meta_value ) > 1) dup
ON wp_postmeta.meta_value = dup.meta_value
WHERE post_id NOT IN (
SELECT
MAX(post_id) AS save_this_post_id
FROM
wp_postmeta
WHERE meta_key = 'meta_key_name'
GROUP BY meta_value
HAVING COUNT(meta_value) > 1
)
);
DELETE pm
FROM wp_postmeta pm
LEFT JOIN wp_posts wp ON wp.ID = pm.post_id
WHERE wp.ID IS NULL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment