I’m trying to setup a shortcode to show a single random user each time the page is refreshed. I’ve been successful in displaying all users or a select user by the user ID.
Here is my shortcode as it is now:
//* Shortcode for getting users
function list_of_users( $atts ) {
extract( shortcode_atts(
array(
'display' => 'all',
'user' => '30'
),
$atts
));
switch ( $display ) {
case 'all':
$content = display_all_users();
break;
case 'single':
$content = display_single_user( (int) $user );
break;
case 'rotate':
$content = display_rotate_users();
break;
default:
break;
}
return $content;
}
add_shortcode('staff', 'list_of_users');
Here’s the function to display all users:
function display_all_users(){
$args = array(
'orderby' => 'ID',
'order' => 'ASC'
);
$users = get_users( $args );
$html = '<ul class="staff">';
foreach( $users as $user ){
$user_info = get_userdata($user->ID);
$html .= '<li>';
$html .= '<a href="'.get_home_url().'/author/'.$user_info->user_nicename.'" class="staff-image">';
$html .= mt_profile_img( $user->ID, array('size' => '250x250','echo' => false));
$html .= '</a>';
$html .= '<div class="staff-info"><a href="'.get_home_url().'/author/'.$user_info->user_nicename.'" class="staff-name"><h2>'.$user->display_name.'</h2></a>';
$html .= '<div class="service-certs">';
$html .= get_field('certifications','user_'.$user->ID);
$html .= '</div>';
$html .= '<p class="service-excerpt">';
$html .= get_field('short_bio','user_'.$user->ID);
$html .= '</p>';
$html .= '<a href="'.get_home_url().'/author/'.$user_info->user_nicename.'" class="more-staff-bio">Read more from ' . $user_info->user_firstname . '</a></div><div style="clear: both;"></div>';
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
Here’s the function to show a single user by ID:
function display_single_user( $user_id = 30 ){
$html = '<div class="home-profile-image">';
$html .= mt_profile_img( $user_id, array('size' => '175x175','echo' => false));
$html .= '</div><div class="home-short-bio">';
$html .= get_field('short_bio','user_'.$user_id);
$html .= '</div><a href="'.get_home_url().'/our-team/" class="button">Read more staff bios</a>';
return $html;
}
Where I’m stuck is to take the list of all users and then randomizing the user id to then use to display certain info. I would like to keep the output of the single user (above) for this random user…it’s just a matter of how to get that random ID.
Any suggestions on how to accomplish this?
By default WordPress allow only order ASC and DESC. However, you can use
WP_User_Query
and the actionpre_user_query
to adjust the query (that is passed by reference) just like you want.This is efficient because you get only one user, not all.
Something like this should get you a random user. Not tested.
PHP: array_rand – Manual