W3TC page cache and spam comments

A few weeks ago I was examining Bernews performance and saw that the W3 Total Cache (W3TC) page cache was being invalidated far more often than I expected. This was happening even when no stories were being posted or comments approved.

It turns out that the page cache was being invalidated when a new comment was being submitted. Unfortunately Bernews receives a spam comment every few minutes. The excellent Akismet plugin catches all of them but the cached version of the homepage was being constantly invalidated.

I fixed the problem by modifying  W3TC to only purge the page cache when a comment is approved. To do that I had to change the W3_Plugin_PgCache::run() function in wp-content/plugins/w3-total-cache/lib/W3/Plugin/PgCache.php.

I removed these lines:

add_action('comment_post', array(
    &$this,
    'on_comment_change'
    ), 0);
add_action('edit_comment', array(
    &$this,
    'on_comment_change'
    ), 0);
add_action('delete_comment', array(
    &$this,
    'on_comment_change'
    ), 0);
add_action('wp_set_comment_status', array(
    &$this,
    'on_comment_status'
    ), 0, 2);
add_action('trackback_post', array(
    &$this,
    'on_comment_change'
    ), 0);
add_action('pingback_post', array(
    &$this,
    'on_comment_change'
    ), 0);

And added these instead:

add_action('comment_unapproved_to_approved', array(
    &$this,
    'on_comment_change'
    ), 0);
add_action('comment_spam_to_approved', array(
    &$this,
    'on_comment_change'
    ), 0);
add_action('comment_deleted_to_approved', array(
    &$this,
    'on_comment_change'
    ), 0);
add_action('comment_approved_to_deleted', array(
    &$this,
    'on_comment_change'
    ), 0);
add_action('comment_approved_to_unapproved', array(
    &$this,
    'on_comment_change'
    ), 0);
add_action('comment_approved_to_spam', array(
    &$this,
    'on_comment_change'
    ), 0);

Note that I did not change the db cache or object cache code! Those caches should be invalidated when a new comment is submitted.

This change greatly decreased the number of times the page cache was invalidated, improving the average response time of the site.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>