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.
Opens WPIDE on
Code
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 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.