Skip to content

Instantly share code, notes, and snippets.

@tc33
Last active July 8, 2022 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tc33/913b251a8c15f0e66894fee70afaaafb to your computer and use it in GitHub Desktop.
Save tc33/913b251a8c15f0e66894fee70afaaafb to your computer and use it in GitHub Desktop.
Handle caching WordPress user counts to avoid slow blocking queries on sites with large user bases. Can be installed directly as an mu-plugin.
<?php
/**
* Returns cached user counts if there are some, otherwise fetches current user counts and stores them for later use.
*
* @param int $count Count to be overridden, will be null when called by pre_count_users.
* @param string $strategy The computational strategy to use when counting the users.
* @param int|null $site_id The site ID to count users for.
*
* @return array Includes a grand total and an array of counts indexed by role strings.
*/
function tc33_cached_user_count( $count, $strategy, $site_id ) {
// Respect any value already set by another filter
if ( ! is_null( $count ) ) {
return $count;
}
$count = get_transient( 'tc33_user_count' );
if ( $count === false ) {
// No cached value, so fetch current user count
$count = tc33_latest_user_count( $strategy, $site_id );
}
return $count;
}
add_filter( 'pre_count_users', 'tc33_cached_user_count', 10, 3 );
/**
* Counts current users as per count_users() and stores the value for use by tc33_cached_user_count() filter.
*
* @param string $strategy Optional. The computational strategy to use when counting the users.
* Accepts either 'time' or 'memory'. Default 'time'.
* @param int|null $site_id Optional. The site ID to count users for. Defaults to the current site.
* @return array Includes a grand total and an array of counts indexed by role strings.
*
* @see count_users()
*/
function tc33_latest_user_count( $strategy = 'time', $site_id = null ) {
// Unhook our filters before fetching the counts
remove_filter( 'pre_count_users', 'tc33_cached_user_count' );
$count = count_users( $strategy, $site_id );
add_filter( 'pre_count_users', 'tc33_cached_user_count', 10, 3 );
// Save the value in our cache for 12 hours
set_transient( 'tc33_user_count', $count, 12 * HOUR_IN_SECONDS );
return $count;
}
@tc33
Copy link
Author

tc33 commented Jul 8, 2022

@mircobabini Yes, WordPress have now addressed the issue in core, so this is no longer required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment