# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: comments, admin, cache
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/perf-cache-comment-counts/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Cache Site-Wide Comment Counts" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
