如何使用 get_users 随机排序用户列表

Mar*_*rco 1 random wordpress

我实际上有一个由post_count. 我想知道是否可以随机排序列表。我知道该get_users功能只允许按'ID', 'login', 'nicename', 'email', 'url', 'registered', 'display_name', 'post_count', 'include','meta_value'

对于get_posts,如果我没记错的话,有一个rand选项可以实现这一点。

这是我的模板的代码:

<?php

/*
Template Name: Display Contributors and Authors
*/

    $args = array(
         'role'    => 'contributor',
         'orderby' => 'post_count',
         'order'   => 'DESC'
    );
 
    // only return users with published posts
	$args['has_published_posts'] = true;
    // run the WP_Query
	$contributors = get_users( $args );

    ?>
Run Code Online (Sandbox Code Playgroud)

Muh*_*lal 5

您可以使用以下代码按兰特注册订单:

add_action( 'pre_user_query', 'my_random_user_query' );

function my_random_user_query( $class ) {
    if( 'rand' == $class->query_vars['orderby'] )
        $class->query_orderby = str_replace( 'user_login', 'RAND()', $class->query_orderby );

    return $class;
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

$args = array(
     'role'    => 'contributor',
     'orderby' => 'rand',
     'order'   => 'DESC'
);
Run Code Online (Sandbox Code Playgroud)

来源