上述答案的另一种选择是添加一列(元键),其中包含可以轻松排序的元值\'orderby\' => \'meta_value\'
在args中。
下面是我编写的一个函数,用于向每个用户添加元值。我把它包括在这里是因为$my_order_ids = array( 3, 4, 6, 2, 5 );
确定用户在查询中应按升序排序。
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\' );
这将使用foreach循环向每个用户的
my_user_order
键,每次递增1。您只需定义
$my_order_ids
按照您希望稍后对其进行排序的顺序。
瞬态就在那里,因此只有当$my_order_ids
已更改(换句话说,仅更新用户一次)。您可能需要注释掉add_action( \'admin_notices\', \'my_order_column\' );
防止瞬态丢失时意外运行。
现在,我们已经设置了新的自定义元键和元值,我们应该可以让查询以这种方式对它们进行排序。
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\' );
在上述示例中,以下输出显示为管理通知:
3
4
6
2
5