Get Users List by Role in WordPress

To get the list of all users in your wordpress blog use the following code:


<?php

	$users = get_users();

?>

This function returns an Array of user objects as follows:

Array
(
    [0] => stdClass Object
        (
            [ID] => 1
            [user_login] => admin
            [user_pass] => ***************************.
            [user_nicename] => admin
            [user_email] => admin@localhost.com
            [user_url] => 
            [user_registered] => 2011-06-25 18:05:28
            [user_activation_key] => 
            [user_status] => 0
            [display_name] => admin
        )

    [1] => stdClass Object
        (
            [ID] => 2
            [user_login] => seema
            [user_pass] => ***************************
            [user_nicename] => seema
            [user_email] => seema@localhost.com
            [user_url] => 
            [user_registered] => 2011-06-25 18:12:53
            [user_activation_key] => 
            [user_status] => 0
            [display_name] => seema
        )

)

You can use a foreach loop to extract the required user information.

For example – if you want to extract only the user names, you would do the following loop

<?php
    
     $users = get_users();

     foreach( $users as $user )
     {
	 	echo $user->user_nicename;
		
		echo '<br />';
        
     }
?>

The above code is fine as long as you want all users in your blog. But when you need users by roles, you will need to pass certain parameters to the function get_users();

Say, you want all users with the role “agent”. The following modified code will get you all the user from role agent

<?php

	$args['role'] = 'agent';
	
	$users = get_users( $args );
?>	

What we are doing here is passing an argument role to the get_users() function telling it to return only those users who belong to the role agent.

You can pass more arguments to the get_users() function to filter the returned users as per your requirements.

For a detailed list of arguments check out this article at wordpress codex

Note that this function is available from WordPress version 3.1 onwards.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>