Last active
July 8, 2022 16:53
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Useless for WP6.0+. https://make.wordpress.org/core/2022/05/02/performance-increase-for-sites-with-large-user-counts-now-also-available-on-single-site/