-
-
Save jeremyboggs/1295667 to your computer and use it in GitHub Desktop.
<?php | |
/** | |
* Returns users ordered by a given key. | |
* | |
* @param string The meta_key to order by. Default is 'last_name'. | |
* @param string The sort direction. Default is ASC. | |
* @todo Add parameter to skip users with specific IDs | |
* @todo Add parameter to skip users with an empty last name. | |
*/ | |
function get_users_ordered_by_usermeta($metaKey = 'last_name', $sortDir = 'ASC') | |
{ | |
global $wpdb; | |
$select = "SELECT * FROM $wpdb->users | |
INNER JOIN $wpdb->usermeta ON ($wpdb->users.ID = $wpdb->usermeta.user_id) | |
WHERE $wpdb->usermeta.meta_key = '$metaKey' | |
ORDER BY $wpdb->usermeta.meta_value $sortDir"; | |
$users = $wpdb->get_results($select); | |
return $users; | |
} |
Hey! Use the WP_User_Query class.
I should follow the WP changelog more closely. Missed this in 3.1, and didn't know about the (now deprecated) WP_User_Search class.
Looking at WP_User_Query class, I cannot figure out a way to use it and return users ordered by their last name, or any other field in the usermeta table.
Yeah, that's not formally supported. It would be really nice if they put a couple of filters in place so that you could do it correctly. As it stands, you could add a filter to 'query' just before the WP_User_Query is built, and unhook it right afterward (so that you don't accidentally filter any other queries). That filter would then do some sort of preg_replace() to redo the ORDER BY clause. Lame and hackish, but probably the only viable way to do it.
Another sorta hackish way is the following. Run your own custom query against the usermeta table to get the proper order (something like $wpdb->get_results( $wpdb->prepare( "SELECT user_id, meta_value FROM $wpdb->usermeta WHERE meta_key = 'whatever_your_meta_key_is' ORDER BY meta_value DESC" ) ); (because this doesn't include any joins or subqueries, it'll be really fast). That'll give you an array in the correct order. Loop through and get the user_ids out of this array, and do a WP_User_Query that has these user ids as the 'include' parameter. Then, once you get the results, use uasort() to reorder the results of WP_User_Query according to the first query order.
Both of these methods are way more complicated than what you did above :) WP_User_Query is nice to use if you can, though, because it's built to cache, and because it returns a lot of useful information in a structure that is predictable.
Would like to update this to return the user array with the usermeta data for each user too, instead of having to separately get that with 'get_usermeta()' when looping users.