Sort a list of WordPress users by a custom meta field

Thoughts from the team
By    | October 9, 2012 | Code Snippets,

So you want to sort a list of WordPress users by a custom field.  You’ve had a look at get_users and noticed that it doesn’t support the same sorting options as get_posts. You can’t just define meta_key => “foo” and orderby => “meta_value” in your query args.  So how do you do it?

We can add the “all_with_meta” fields option to our get_users query. This will add each of our custom meta fields as a function on the returned User objects. If you do a var_dump you wont see them, but if you call them, they are there!

With the extra fields loaded into our object, we can use a custom sort in PHP to order the list.

  $args = array('fields' => 'all_with_meta');

  $users = get_users($args);

  // We'll need a custom comparison function to order by the custom field
  function sort_team($a, $b){
    return ($a->order < $b->order) ? -1 : 1;
  }

  // Sort using our custom comparison function
  usort($users, "sort_team");

  foreach ($users as $user){
     // Do your thing here
  }

Simple.

More like this