I adapted a little a function to display a number of random users with their avatars with a shortcode. It works, but something is not good. Sometimes it displays with one user less than I want (just a blank line instead of the first user), sometimes it includes the administrator, although it should not. What is wrong with my code?
add_shortcode( 'random_users', 'display_random_users' );
//Usage: [random_users how_many = 3]
function display_random_users( $atts ) {
extract(shortcode_atts( array( "how_many" => '' ), $atts ) );
$args = array(
'orderby' => 'ID',
'role' => 'subscriber',
'fields' => 'ID'
);
$users = get_users( $args );
$users = array_rand( $users, $how_many );
foreach ( $users as $userID ) {
echo '<a href="' .
bp_core_get_user_domain( $userID ) . '">' .
bp_core_fetch_avatar( array( 'item_id' => $userID ) ) . '<br />' .
xprofile_get_field_data( '1', $userID ) . '</a><br />';
}
}
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.