[wp-hackers] Seeking SQL advice to identify performance problem

Simon Blackbourn piemanek at gmail.com
Wed Jun 20 13:52:02 UTC 2012


>
>
> > I have a query that I have used in a couple plugins that someone on this
> > mailing list helped me with several years ago.  I want to retrieve the
> list
> > of Users, including their ID, username, display name, first name, and
> last
> > name so I can present the information in a form in a way that is easily
> > readable.
>


You can use the get_users() function [1] with the 'fields' parameter set
to 'all_with_meta', and then perform a usort on the results:

$args = array(
'number'     => 1000000, //  unfortunately you can't use -1 here
'fields'     => 'all_with_meta', // required
                        'exclude' => array( 1 ) // user IDs to exclude
);

$user_list = get_users( $args );

if ( ! empty( $user_list ) ) {
usort( $user_list, 'sort_my_users_by_lastname' );
foreach ( $user_list as $user ) {
                // do stuff here...
}
}

// .....

function  sort_my_users_by_lastname( $a, $b ) {

if ( $a->last_name == $b->last_name ) {
return 0;
}

return ( $a->last_name < $b->last_name ) ? -1 : 1;

}


Ideally you would paginate using the 'number' and 'offset' fields to make
it more efficient, but if you need all users in one go as I did, sorted by
lastname, it still seems to work very well. I've got this running on a site
without just short of 1000 users and the query takes 1/100th of a second.

Simon

[1] http://codex.wordpress.org/Function_Reference/get_users


More information about the wp-hackers mailing list