1

I'm using WP_User_Query to bring back a list of users. I'm passing a list of specific users to be included in results. For example:

    $user_ids = array( 1, 5, 9, 61, 24, 12 );

    $args = array(
        'include' => $user_ids,
        'count_total' => true,
        'search' => sanitize_text_field( $_GET['phrase'] )
    );

    $query = new WP_User_Query( $args );

Results are currently ordered by user_login. How can I modify my query so that the results returned are ordered by my $user_id array? For example, if 3 users are to be returned (let's say IDs 5, 61 and 12), then user 5 should be displayed first, user 61 second and user 12 third.

Ref: http://codex.wordpress.org/Class_Reference/WP_User_Query

2 Answers 2

1

I think that instead of dealing with complex SQL queries and ways to make WordPress use them, a simple uasort can do the trick:

$uids = array( 1 );

$user_query = new WP_User_Query( array( 'include' => $uids ) );

$users = (array) $user_query->results;

usort( $users, function( $a, $b ) use( $uids ) {
  return array_search( $a->ID, $uids) < array_search( $b->ID, $uids ) ? -1 : 1;
} );

// use as usual
foreach ( $users as $user ) {
    echo '<p>' . $user->display_name . '</p>';
}
1
  • out of interest, is there a way to achieve the same effect by modifying the actual query (instead of using usort after the query has run)? Commented Oct 30, 2014 at 21:35
2

I know it's late, but if someone interested try: $args['orderby'] = 'include';

Worked for me..

1
  • 2
    Hi Dima, thanks for your answer. Would you mind editing it to explain further why this works/what it does? Thanks very much!
    – Tim Malone
    Commented May 10, 2016 at 23:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.