在WordPress中,我想统计所有用户,使用WP_User_Query向用户显示偏移量和限制。因此,我正在使用ajax,用户可以选择要显示多少用户并应该显示分页。
为此,我正在使用它
$limit_args = array( 'number' => $request['length'], 'offset' => $request['start'] );
$args = array( 'orderby' => 'display_name', 'order' => 'ASC' );
$all_users = new WP_User_Query( $args );
$total_users = count($all_users->get_results());
$filtered = count($all_users->get_results());
我在这里获得了总用户
但是为了限制用户并且出于限制,我再次使用WP_User_Query。像这样
$data = array()
if( $filtered > 0 ) {
$args = array_merge($args, $limit_args);
$all_users = new WP_User_Query( $args );
foreach ( $all_users->get_results() as $user ) {
$user_data = array();
$user_id = $user->ID;
$user_info = get_userdata($user_id);
$user_data[] = $user->display_name;
array_push($data, $user_data);
}
}
print_r($data); //Gets user data
因此,如果您看到我两次使用WP_User_Query()。有人可以告诉我一次如何使用偏移量并一次限制总用户数。
答案 0 :(得分:0)
因此,我研究了WP_User_Query
的行为和相关的get_total
函数,并意识到尽管set
函数可以工作,但您实际上不需要使用它。
使事情顺利进行所需的代码如下:
$user_count = 10;
$offset = 0;
if(isset($request['length'])) {
$user_count = $request['length'];
}
if(isset($request['start'])) {
$offset = $request['start'];
}
$args = array('number' => $user_count, 'offset' => $offset, 'orderby' => 'display_name', 'order' => 'ASC');
$all_users = new WP_User_Query( $args );
$total_users = $all_users->get_total(); //use this for pagination
$filtered = count($all_users->get_results()); //use this for determining if you have any users, although it seems unnecessary
$data = array()
if( $filtered > 0 ){
foreach ( $all_users->get_results() as $user ) {
$user_data = array();
$user_id = $user->ID;
$user_info = get_userdata($user_id);
$user_data[] = $user->display_name;
array_push($data, $user_data);
}
}
print_r($data); //Gets user data
如果您不想默认设置number
和offset
参数,则可以执行以下操作:
$args = array( 'orderby' => 'display_name', 'order' => 'ASC' );
$all_users = new WP_User_Query( $args );
$total_users = $all_users->get_total();
$all_users->set('number', $request['length']);
$all_users->set('offset', $request['start']);
$all_users->prepare_query();
$all_users->query();
$filtered = count($all_user->get_results());
//And whatever you want from here on
祝你好运!