Efficiency on displaying random authors based on large database

If you are concerned about efficiency, you might want to use the Transients API to store the query. Storing something that you want to randomize might seem counter-intuitive, but if you store the entire query, you can always randomize and manipulate the resulting array to get the results you want.

Here’s how to get all the subscribers and store them in a transient, with a but of straight PHP at the end to shuffle/randomize the result and then pick off the first 5 results using array_slice()

if ( false === ( $users = get_transient( 'get_all_subscribers' ) ) ) {
     // this code runs when there is no valid transient set

    $args  = array(
        'role'   => 'subscriber'
    );

    $wp_user_query = new WP_User_Query( $args );

    $users = $wp_user_query->get_results();

    set_transient( 'get_all_subscribers', $users );
}

// proceed with data normally
// randomize the stored result
shuffle( $users );
$rand_users = array_slice( $users, 0, 5 );

var_dump( $rand_users );

and then to make sure the transient is up to date, we’ll delete it when a user is updated or added:

// Create a simple function to delete our transient
function delete_all_subscribers_transient() {
     delete_transient( 'get_all_subscribers' );
}
// Add the function to the profile_update and user_registration hooks
add_action( 'profile_update', 'delete_all_subscribers_transient' );
add_action( 'user_register', 'delete_all_subscribers_transient' );

Leave a Comment