如何获得按角色分配的用户列表?


Answers:


18

可能有一些不同的方法来执行此操作,但最正确的方法是遵循以下方法。

<?php

$args = array(
    'role'    => 'Your desired role goes here.',
    'orderby' => 'user_nicename',
    'order'   => 'ASC'
);
$users = get_users( $args );

echo '<ul>';
foreach ( $users as $user ) {
    echo '<li>' . esc_html( $user->display_name ) . '[' . esc_html( $user->user_email ) . ']</li>';
}
echo '</ul>';

?>

3

这里是对角色进行分组的简单方法。

$wp_roles = wp_roles();
$result   = count_users();

foreach ( $result['avail_roles'] as $role => $count )
{
    if ( 0 == $count )
        continue; //pass role none

    $args = array(
        'role' => $role
    );

    $users = get_users( $args );
    $user  = array();
    for ( $i = 0; $i < $count ; $i++ )
        $user[] = esc_html( $users[ $i ]->display_name ); //show display name

    //output
    echo wp_sprintf( '<h2>%1$s</h2><ul><li>%2$s</li></ul>',
        esc_html( $wp_roles->role_names[ $role ] ),
        implode( '</li><li>', $user )
    );
}

2

找到具有Ultimate Member Plugin角色的用户时,必须在角色值中添加“ um_”。例如,您在Ultimate Membership Plugin中创建了角色名称“ Client”,则$ args将是

$args = array(
    'role'    => 'um_client',
    'orderby' => 'user_nicename',
    'order'   => 'ASC'
);

0

扩展Raja的答案,您还可以编写一个辅助函数来为您处理:

<?php
# This goes in functions.php
function get_users_by_role($role, $orderby, $order) {
    $args = array(
        'role'    => $role,
        'orderby' => $orderby,
        'order'   => $order
    );

    $users = get_users( $args );

    return $users;
}
?>

然后,要使用户具有特定角色,您只需执行以下操作:

<?php $users = get_users_by_role('Your role', 'user_nicename', 'ASC'); ?>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.