How to display random users with avatars

I am not sure why your query is returning more IDs than necessary. The $args for get_users look correct.

By default get_users does not support orderby=rand, but you can overwrite that option. See below:

function random_user_query( &$query )
{
    $query->query_orderby = "ORDER BY RAND()";
}

// Usage: [random_users how_many = 3]
add_shortcode( 'random_users', 'display_random_users' );
function display_random_users( $atts ) {

    shortcode_atts( array( "how_many" => '', ), $atts );

    // Create a function to override the ORDER BY clause
    add_action( 'pre_user_query', 'random_user_query' );

    $users = get_users( array(
        'role'    => 'subscriber',
        'fields'  => 'ID',
        'orderby' => 'rand',
        'number'  => $atts['how_many'],
    ) );

    foreach ( $users as $userID ) {
        printf( 
            '<a href="https://wordpress.stackexchange.com/questions/174107/%s">%s<br />%s</a><br />',
            bp_core_get_user_domain( $userID ),
            bp_core_fetch_avatar( array( 'item_id' => $userID ) ),
            xprofile_get_field_data( '1', $userID )
        );
    }

    // Remove the hook
    remove_action( 'pre_user_query', 'random_user_query' );
}

This way, you only query $how_many users, instead of querying all users and then filtering out $how_many.

I found this hook here.

Leave a Comment