My pretty face [ László Monda's Blog ]
Exploring the cyberspace, one quadrant at a time!

WordPress Comment Counter Hell

The comment counters of my articles have been messed up. I've noticed this thing several months ago and it's probably related to WordPress updates. I set the counters manually within phpMyAdmin for the first time it happened, but I got pretty pissed off when it already happened later so I decided to fix this mess. I've googled around for the solution and found a pretty good script to solve the problem which was a bit buggy and incomplete, so I fixed it.

Here you are:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
< ?php
 
if (!file_exists('../wp-config.php')) {
    die('There doesn\'t seem to be a wp-config.php file. Double check ' .
        'that you updated wp-config-sample.php with the proper database ' .
        'connection information and renamed it to wp-config.php.');
}
 
require('../wp-config.php');
 
$posts_table = $table_prefix . 'posts';
$comments_table = $table_prefix . 'comments';
 
print 'Updating comment counters...<br>';
 
$query = 'SELECT count(comment_id) AS comment_count, comment_post_id ' .
         "FROM $comments_table GROUP BY comment_post_id";
 
$comments = $wpdb->get_results($query);
 
$where = '';
$first = true;
 
if ($comments) {
    foreach ($comments as $comment) {
        $id = $comment->comment_post_id;
        $count = $comment->comment_count;
 
        $query = "UPDATE $posts_table SET comment_count = $count WHERE ID = $id";
        $wpdb->query($query);
 
        if (!$first) {
            $where .= 'AND ';
        }
        $where .= "ID != $id ";
        $first = false;
    }
}
print count($comments) . ' articles has comments.  Their comment ' .
      'counters have been explicitly set.<br />';
 
$query = "UPDATE $posts_table set comment_count = 0 WHERE $where";
$results = $wpdb->get_results($query);
print count($results) . ' comment counters needed to be zeroed of the ' .
      'articles which doesn\'t have any comments.<br />All done!<br />';
 
?>

You can fetch it here. Just copy it to your "wp-admin" directory and point your browser to its URL.

Leave a Reply

Line and paragraph breaks automatic.
XHTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">