Search code examples
wordpresstableviewfrontenduser-roles

Get a table of users by their role


I would like to have a table with headers in which the users are listed and also add a user specific link.

I found the code underneath which I changed a little, but I wasn't able to change it to table mode.

Also I have a problem with the link, I want the link to have the used_id behind it, but I don't know where to implement it.

 <?php
 $args = array(
    'role'    => 'Agente',
    'orderby' => 'user_nicename',
    'order'   => 'ASC'
);
 $users = get_users( $args );
 $impersonate_url   = admin_url("?impersonate=$user_id");

 echo '<ul>';
 foreach ( $users as $user ) {
    echo '<li>' . esc_html( $user->display_name ) . '[' . "<a href='$impersonate_url'>"  . ']</li>';
 }
 echo '</ul>';

?>

Solution

  • I hope you are asking for displaying user name and link in tabular form. So I have reformatted your code to display data in table. Also $impersonate_url is taken inside the foreach loop.

    $args = array(
        'role'    => 'Agente',
        'orderby' => 'user_nicename',
        'order'   => 'ASC',
    );
    $users = get_users( $args );
    if ( ! empty( $users ) ) {
        echo '<table>';
        echo '<tr><th>Name</th><th>Profile</th></tr>';
        foreach ( $users as $user ) {
            echo '<tr>';
            $impersonate_url = admin_url( '?impersonate=' . $user->ID );
            echo '<td>' . esc_html( $user->display_name ) . '</td>';
            echo '<td>' . '<a href="' . esc_url( $impersonate_url ) . '">' . 'Link</a></td>';
            echo '</tr>';
        }
        echo '</table>';
    }
    

    Edit: Add table heading.