Fix number of comments in WordPress.

The plugin “Did you pass Maths?” that I am using to prevent spam had an annoying bug: rejected posts still incremented the comment count. So I have made a little program to update my database with correct number of comments.

Here it is.

<?php

require('www/journal/wp-config.php');

mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_NAME);

function get_real_nb_comm($post_id) {
    $sql = "SELECT COUNT(*) FROM wp_comments WHERE comment_post_ID = $post_id";
    $query = mysql_query($sql);
    $row = mysql_fetch_row($query);
    return $row[0];
}

function set_nb_comm($post_id, $nb) {
    $sql = "UPDATE wp_posts SET comment_count = $nb WHERE ID = $post_id";
    mysql_query($sql);
}

$sql = 'SELECT ID FROM wp_posts ORDER BY ID';
$query = mysql_query($sql);

while($row = mysql_fetch_row($query)) {
    set_nb_comm($row[0], get_real_nb_comm($row[0]));
}

?>

One Response to “Fix number of comments in WordPress.”

  1. Guillaume Says:

    There’s also that plug-in I just saw: http://dev.wp-plugins.org/wiki/MathCommentSpamProtection

    ‘dunno if it has the same problem or not, if it’s better or not than the other anyway… but it might be interesting who knows :)

Leave a Reply

CAPTCHA Image