Using WordPress ‘cache_users()’ PHP function

The cache_users() WordPress PHP function retrieves information for user lists, eliminating the need for multiple queries by get_userdata(). It essentially helps in caching user data, enhancing the efficiency of your WordPress site.


Here’s a simple example of how to use the cache_users() function:

$user_ids = array(1, 2, 3, 4, 5);

In this example, an array of user IDs is created and then passed to the cache_users() function. This will cache the data of users with these IDs.


  • $user_ids (int array) – This required parameter is a list of User ID numbers.

More information

See WordPress Developer Resources: cache_users()


Caching User Data

In this example, we’re caching data for users 1, 2, and 3.

$user_ids = array(1, 2, 3);

Using with get_userdata()

You can use cache_users() before get_userdata() to prevent multiple queries.

$user_ids = array(1, 2, 3);

foreach($user_ids as $id) {
  $user = get_userdata($id);
  echo 'User email: ' . $user->user_email;

In the above example, user data is cached before looping through the user IDs and fetching user data with get_userdata().

Caching Data for a Large Number of Users

If you have a large number of users, you can cache their data in chunks to avoid overloading your server.

$user_ids = range(1, 1000);
$user_ids_chunks = array_chunk($user_ids, 200);

foreach($user_ids_chunks as $chunk) {
  // process users here...

In this example, user IDs from 1 to 1000 are divided into chunks of 200, and each chunk is then cached.

Caching User Data from a Query

You can cache user data directly from a query.

$args = array(
  'role' => 'subscriber',
  'fields' => 'ids',
$subscribers = get_users($args);

In this example, we’re getting all subscriber IDs using get_users() and then caching their data.

Caching User Data for Logged-In Users

You can use cache_users() to cache data for all logged-in users.

$logged_in_users = get_users(array(
  'fields'  => 'ids',
  'number'  => 0,
  'who'     => 'online',


In the above example, we’re fetching IDs of all logged-in users and then caching their data.