I am trying to get an array of site users sorted by a custom meta value (an int).
I can query the users just fine and get them back to use in a foreach. I currently have the query results come back sorted already by display_name from the users table. I want it to sort by the custom usermeta value.
Any ideas on how to modify this query to get this done?
function get_all_top_members() {
global $wpdb;
$gather_users = "SELECT * FROM ".$wpdb->prefix."users ORDER BY display_name ASC";
$all_users = $wpdb->get_results($gather_users);
return $all_users;
}
You won’t get a proper sort on the
meta_value
column because the values stored there aren’t treated as integer values, but you can use a method similar to how it was done it WordPress back when we were usingmeta_value_num
to do sorting, which basically involved adding a number onto the front of the data.This then gives you a proper sort on the meta value column.
Figured you might like a function so you can call it wherever you need it, just pass it the meta key you have setup for users, and optionally change the sort order.
Sort descending.
You’ll get an array of objects returned just like before, so i’ll assume you know how to loop over that data and appropriate it for display, etc…(if not, post a comment).
try :
and change META_KEY_HERE to your meta key
You guys are doing too much work : https://codex.wordpress.org/Class_Reference/WP_User_Query
Like other WP{{Query}} type conventions, you can orderby, limit result count, etc …
https://codex.wordpress.org/Class_Reference/WP_User_Query
edit – Caveat: this assumes you are assigning custom user data to the wp_core anticipated user table(s) – which in the OP it looks like you are. For custom tables, you’ll want to go the $wpdb approach described by another user