Skip to navigation | Skip to content



Get WordPress users by role

There’s a few posts around that reveal a nifty use of the WP_User_Search class that’s part of WordPress’ core code, in order to select all users that have a specific role (the trick seems to have originated with John Kolbert).

But… WP_User_Search is only loaded when you’re inside the WP admin area. What about front-end template code?

I decided to track down the SQL that WP_User_Search comes up with for the search (using $wpdb->queries), and write a custom function wrapper which will work the same way wherever.

I’m not quite sure if there’s any advantage to including the use of WP_User_Search as well as the back-up SQL, as they pretty much do the same thing. I dunno.

Anyway, here’s the code. This is for pasting into your theme’s functions.php file. It’ll return an array of user IDs.

function getUsersByRole( $role ) {
	if ( class_exists( 'WP_User_Search' ) ) {
		$wp_user_search = new WP_User_Search( '', '', $role );
		$userIDs = $wp_user_search->get_results();
	} else {
		global $wpdb;
		$userIDs = $wpdb->get_col('
			SELECT ID
			FROM '.$wpdb->users.' INNER JOIN '.$wpdb->usermeta.'
			ON '.$wpdb->users.'.ID = '.$wpdb->usermeta.'.user_id
			WHERE '.$wpdb->usermeta.'.meta_key = \''.$wpdb->prefix.'capabilities\'
			AND '.$wpdb->usermeta.'.meta_value LIKE \'%"'.$role.'"%\'
		');
	}
	return $userIDs;
}

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Want to show me some code? Don't paste long code here, link to a post at pastebin.ca or a similar site. Thanks.

Recent posts

Archives