Skip to content

Instantly share code, notes, and snippets.

@grimmdude
Last active September 23, 2018 18:26
Show Gist options
  • Save grimmdude/5828710 to your computer and use it in GitHub Desktop.
Save grimmdude/5828710 to your computer and use it in GitHub Desktop.
Small script to delete duplicate post comments from a Wordpress database. Backup first bud.
<?php
# First select all comments
$query = "SELECT `comment_ID`, `comment_post_ID`, `comment_content` FROM ".$wpdb->comments." WHERE 1";
$comments = $wpdb->get_results($query);
# Array to hold keeper comment IDs so we don't delete them if there are doops
$keeper_comments = array();
# Now check if each comment has any matching comments from the same post
foreach ($comments as $comment) {
$query = "SELECT `comment_ID` FROM ".$wpdb->comments." WHERE `comment_ID` != ".$comment->comment_ID." AND `comment_post_ID` = ".$comment->comment_post_ID." AND `comment_content` = '".addslashes($comment->comment_content)."'";
$matching_comments = $wpdb->get_results($query);
if ($wpdb->num_rows > 0) {
foreach ($matching_comments as $matching_comment) {
if (!in_array($matching_comment->comment_ID, $keeper_comments)) {
$wpdb->query("DELETE FROM ".$wpdb->comments." WHERE `comment_ID` = ".$matching_comment->comment_ID);
$wpdb->query("UPDATE ".$wpdb->posts." SET `comment_count` = `comment_count` - 1 WHERE `comment_ID` = ".$matching_comment->comment_ID);
}
}
$keeper_comments[] = $comment->comment_ID;
}
}
@iamkingsleyf
Copy link

Does it still work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment