Quantcast
Viewing all articles
Browse latest Browse all 31

Delete duplicate WordPress comments

Image may be NSFW.
Clik here to view.
wordpress-logo-square-256x256
In one of the domain transfers I did for a blog the Disqus migration didn’t go very well resulting in thousands of duplicate comments. To delete these duplicate comments I created a PHP file in the main wordpress directory with the following code:

<?php
require_once('wp-config.php'); global $wpdb, $comment_content, $comments,$comment_ID;
# 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;
}
}

 

It took care of all the problems. Be sure to backup your database before giving this a go, I can’t guarantee this would work for you.


Viewing all articles
Browse latest Browse all 31

Trending Articles