# Cache User Counts on Large Sites

> Caches the per-role user counts shown on the Users screen and dashboard for 12 hours, avoiding a heavy query on sites with many users.

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

## Code

```php
add_filter( 'pre_count_users', function ( $result, $strategy, $site_id ) {
    static $busy = false;

    if ( null !== $result || $busy ) {
        return $result;
    }

    $key    = 'wpide_user_counts_' . (int) $site_id . '_' . $strategy;
    $cached = get_transient( $key );

    if ( is_array( $cached ) ) {
        return $cached;
    }

    $busy   = true;
    $counts = count_users( $strategy, $site_id );
    $busy   = false;

    set_transient( $key, $counts, 12 * HOUR_IN_SECONDS );

    return $counts;
}, 10, 3 );

$wpide_flush_user_counts = function () {
    foreach ( array( 'time', 'memory' ) as $strategy ) {
        delete_transient( 'wpide_user_counts_' . get_current_blog_id() . '_' . $strategy );
    }
};

add_action( 'user_register', $wpide_flush_user_counts );
add_action( 'deleted_user', $wpide_flush_user_counts );
add_action( 'set_user_role', $wpide_flush_user_counts );
```

## Notes

Counts refresh when users are added, deleted or change role, and at least every 12 hours.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Cache User Counts on Large Sites" 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/
