Selecting Randon Users

Posted within Development on

Unlike the get_posts() and get_pages() functions within WordPress, get_users() doesn’t provide a way to return a random selection of users (the results can only be sorted by ‘nicename’, ’email’, ‘url’, ‘registered’, ‘display_name’, or ‘post_count’). For several projects, usually for sidebar widgets, theres been a need to return a randomly sorted sub-set of users, so I wrote the following custom function:

if ( !function_exists( 'get_random_users' ) ) {
	function get_random_users( $args = array() ) {
		$random_users = array();
		$number = 10;

		$defaults = array( 'number' => $number, 'exclude_administrators' => FALSE );
		$args = wp_parse_args( $args, $defaults );
		$number = $args['number'];

		unset( $args['number'] );

		if ( $args['exclude_administrators'] == TRUE ) {
			$administrators = get_users( array( 'role' => 'administrator' ) );

			if ( $administrators && !is_wp_error( $administrators ) ) {
				$exclude = array();

				foreach( $administrators as $user ) {
					$exclude[] = $user->ID;
				}

				$args['exclude'] = $exclude;
			}

		}

		$users = get_users( $args );

		if ( $users && !is_wp_error( $users ) ) {
			$total_users = count( $users );
			$number = ( $total_users > $number ) ? $number: $total_users;

			if ( $total_users == 1 ) {
				$random_users = $users;
			} elseif ( $total_users > 1 ) {
				shuffle( $users );
				$random_users = array_slice( $users, 0, $number );
			}

		}

		return $random_users;
	}
}

Essentially it works and accepts the same parameters as get_users(), but I have included an option that allows you to exclude Administrators from the returned array. I’m sure the code can be improved – and I probably will do when I get the chance, but for now it does the job.

Alternatively, the following two lines of code, added into the wp-includes/user.php file at line 446, would remove the need for the above function and allow ‘rand’ to be a valid value for the ‘orderby’ parameter.

} elseif ( 'rand' == $qv['orderby'] ) {
	$orderby = 'RAND()';

But I would never condone editing the core WordPress files.