Cache Site-Wide Comment Counts
Stores the comment totals that WordPress shows in the admin menu, toolbar and dashboard for 10 minutes, avoiding a slow counting query on every admin page view on sites with many comments.
Opens WPIDE on
Code
add_filter( 'wp_count_comments', function ( $stats, $post_id ) {
if ( ! empty( $stats ) || (int) $post_id ) {
return $stats;
}
$cached = get_transient( 'wpide_comment_counts' );
if ( is_object( $cached ) ) {
return $cached;
}
// Same numbers wp_count_comments() would compute, stored for reuse.
$counts = (object) get_comment_count( 0 );
$counts->moderated = $counts->awaiting_moderation;
unset( $counts->awaiting_moderation );
set_transient( 'wpide_comment_counts', $counts, 10 * MINUTE_IN_SECONDS );
return $counts;
}, 10, 2 );
$wpide_flush_comment_counts = function () {
delete_transient( 'wpide_comment_counts' );
};
add_action( 'wp_insert_comment', $wpide_flush_comment_counts );
add_action( 'transition_comment_status', $wpide_flush_comment_counts );
add_action( 'deleted_comment', $wpide_flush_comment_counts );
add_action( 'trashed_comment', $wpide_flush_comment_counts );
add_action( 'spammed_comment', $wpide_flush_comment_counts );
Notes
The cache is cleared whenever a comment is added, approved, spammed or deleted, so counts stay accurate.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.