One alternative offered to the above answer is to add a column (meta key) with meta values which can easily be sorted with 'orderby' => 'meta_value'
in the args.
Here is a function I wrote to add the meta values to each user. I'm including it here because $my_order_ids = array( 3, 4, 6, 2, 5 );
determines the ascending order users should be sorted by in your query.
function my_order_column() {
// Defines the user IDs to be updated.
// Use the desired order when you define this.
$my_order_ids = array( 3, 4, 6, 2, 5 );
// Runs only when $my_order_ids has changed by comparing
// it to _transient_my_order_column.
if (false === get_transient('my_order_column') ||
get_transient('my_order_column') !== $my_order_ids) {
// Updates _transient_my_order_column
set_transient('my_order_column', $my_order_ids);
// The first user
$order_id = 1;
// Add an integer value for each user
foreach ($my_order_ids as $user_id) {
// Sets/updates the value of my_user_order
update_user_meta( $user_id, 'my_user_order', $order_id );
// Confirms that the new value of my_user_order matches the
// current value of $order_id
if ( get_user_meta($user_id, 'my_user_order', true ) != $order_id )
wp_die('An error occurred');
$order_id++;
}
?><div class="updated">
<p><?php echo var_dump($my_order_ids) . '<br />Updated!'; ?></p>
</div><?php
}
}
add_action( 'admin_notices', 'my_order_column' );
This uses a foreach loop to add a new integer value to each user's my_user_order
key, incrementing by 1 each time. All you need to do is define $my_order_ids
in the order you want them to be sorted later.
The transient is just there so that the updates will only run when the values of $my_order_ids
has changed (in other words, only update users once). You may want to comment out add_action( 'admin_notices', 'my_order_column' );
to prevent it from running unexpectedly if the transient is lost.
Now that our new custom meta key and meta values are set, we should have no problem getting the query to order them this way.
function my_user_query() {
$args = array(
'orderby' => 'meta_value', /***************************************/
'order' => 'ASC', /***Added orderby, order and meta_key***/
'meta_key' => 'my_user_order', /***************************************/
// Note: 'include' does not affect how output will be ordered.
// array( 6, 5, 3, 2, 4 ) would still be ordered by meta_value.
'include' => array( 3, 4, 6, 2, 5 ),
'count_total' => true,
'search' => sanitize_text_field( $_GET['phrase'] )
);
$query = new WP_User_Query( $args );
?>
<div class="updated">
<p><?php foreach( $query->results as $user ) {
echo $user->ID . '<br />'; } ?></p>
</div>
<?php wp_reset_query();
}
add_action( 'admin_notices', 'my_user_query' );
In the above example, the following output is displayed as an admin notice:
3
4
6
2
5