How to Get Users in WordPress (+Shortcode to Print Users in a List)

3 from 5
from 2 user
(Rate this post)

WordPress get_users function retrieves users based on given filters and order. This function will return the list of users in an array. WP developers can use the given array to print a List of WordPress users in a shortcode. We're going to review the get_users syntax, try the function usage, and create a shortcode to print a list of users whenever we want!

List users in WordPress using the get_users function

The result of executing the WordPress get_users function is an array of user IDs or objects.

This function is super flexible. WP developers can determine the type of returned value, fields, query filters, order, and a bunch of other stuff we’ll get into shortly by specifying an array of optional arguments.

get_users function syntax

This WordPress function receives an array of arguments to customize the result set for you.

get_users(array $args = array())

As you can see, because $args has the default value of array(), $args is an optional parameter.

The optional $args parameter accepts a variety of options which I’ll explain after the example.

get_users function example: Print list of all users in WP

To print all users (including admin users) in an HTML list, use the below code:

$args = array(); //define arguments if you need
$users = get_users($args);

$listHtml = '<ul>';
foreach($users as $user){
	$listHtml .= '<li>'
	. 'ID: '.$user->data->ID."<br />"
	. 'Username: '.$user->data->user_login."<br />"
	. 'Nice Name: '.$user->data->user_nicename."<br />"
	. 'Display Name: '.$user->data->display_name."<br />"
	. 'Email: '.$user->data->user_email."<br />"
	. 'URL (website): '.$user->data->user_url."<br />"
	. 'Registration Date: '.$user->data->user_registered."<br />"
	. '<li>';
}
$listHtml .= '</ul>';

echo $listHtml;

How to set arguments for get_users function to sort and filter the result?

The get_users function actually executes WP_User_Query under the hood.

You can define arguments to query users based on your needs.

Here is the list of all possible arguments to set for the get_users function:

$args = array(
            'blog_id'             => 1,
            'role'                => '',
            'role__in'            => array(),
            'role__not_in'        => array(),
            'capability'          => '',
            'capability__in'      => array(),
            'capability__not_in'  => array(),
            'meta_key'            => '',
            'meta_value'          => '',
            'meta_compare'        => '',
            'include'             => array(),
            'exclude'             => array(),
            'search'              => '',
            'search_columns'      => array(),
            'orderby'             => 'login',
            'order'               => 'ASC',
            'offset'              => '',
            'number'              => '',
            'paged'               => 1,
            'count_total'         => true,
            'fields'              => 'all',
            'who'                 => '',
            'has_published_posts' => null,
            'nicename'            => '',
            'nicename__in'        => array(),
            'nicename__not_in'    => array(),
            'login'               => '',
            'login__in'           => array(),
            'login__not_in'       => array(),
        );

Explaining above attributes:

  • blog_id -> to set blog id (int), default is the current blog (do not need to set it for a normally installed WP)
  • role -> to get users with a specified role
  • role__in -> accepts array to get users of many roles (array values)
  • role__not_in -> accepts array to get users without specified roles (array values)
  • capability -> to specify the capability of users you want to get
  • capability__in -> accepts array to get users with specified capabilities (array values)
  • capability__not_in -> accepts array to get users without specified capabilities (array values)
  • meta_key -> to filter users based on a meta information set on the user object (meta_value required)
  • meta_value -> to filter users based on value of the key defined in meta_key
  • meta_compare -> to set the comparison operation to compare meta_value with provided data in the database for meta_key label
  • include -> to include an array of user IDs in the query
  • exclude -> to exclude an array of user IDs from the query
  • search -> to search users based on a keyword match in search_columns
  • search_columns -> default value is empty. If left empty, search tries to determine the search column based on the search keyword.
  • orderby -> default is ‘login’, possible values: ‘ID’, ‘display_name’, ‘name’, ‘include’, ‘user_login’ ,’login’, ‘login__in’, ‘user_email, ’email’ , ‘user_registered’, ‘registered’, ‘post_count’
  • order -> default direction is ASC, and you can change it to DESC for reverse order
  • offset -> Useful for list pagination. it receives an integer which determines how many users to skip before fetching the list from the database
  • number -> limit the number of users you want to retrieve
  • paged -> to determine if pagination is active for this query or not. Default is true.
  • count_total -> default is true
  • fields -> to determine what field you need as a return. default is all. It can be a single field or an array of available user fields (ex: ‘ID’, ‘display_name’, ‘user_login’, ‘user_nicename’, ‘user_email’, ‘user_url’, ‘user_registered’, ‘user_pass’, ‘user_activation_key’, ‘user_status’)
  • who -> only possible value is ‘authors’. The other option is the default value which is all users.
  • has_published_posts -> to get only authors with published posts
  • nicename -> to filter users based on nice name
  • nicename__in ->it accepts an array to filter users based on a collection of nice names
  • nicename__not_in -> it accepts an array to exclude users based on a collection of nice names
  • login -> to get an specific user with specified username
  • login__in -> it accepts an array to filter users based on a collection of usernames
  • login__not_in -> it accepts an array to exclude users based on a collection of usernames

What information can I get from WP_User objects?

WP_User object contains all information about a user in WordPress. Check out the below attributes to know if it fits your needs:

WP_User Object
	(
		[data] => stdClass Object
			(
				[ID]
				[user_login]
				[user_pass]
				[user_nicename]
				[user_email]
				[user_url]
				[user_registered]
				[user_activation_key]
				[user_status]
				[display_name]
			)
			
		[ID]
		[caps] => Array()
		[cap_key]
		[roles] => Array()
		[allcaps] => Array()
		[filter]
	)

The data attribute contains all printable information about the user.

The caps, cap_key, roles, and allcaps are the attributes you are looking for if you want to work with WordPress ACL and user permissions. the allcaps is detailed user access to WordPress functionalities.

List users in WP editor using a shortcode

Defining a new shortcode to print all users

Shortcodes are an amazing part of WP development.

Shortcodes are the easiest way to use dynamic content between your regular text when editing WP posts.

In this example, I’ll create a function out of previous code that you hopefully tested. I’ll call it my_custom_users_list().

Then I’ll hook a shortcode to the function, so every time the shortcode is presented in a post’s content, It will print a list of registered users on your website.

-> Add this code to functions.php file of your active template:

//first check if my_custom_users_list is defined before or not.
if(!function_exists('my_custom_users_list')){
	// function that runs when shortcode is called
	function my_custom_users_list() {
		$args = array(); //define arguments if you need
		$users = get_users($args);

		$listHtml = '<ul>';
		foreach($users as $user){
			$listHtml .= '<li>'
			             . 'ID: '.$user->data->ID."<br />"
			             . 'Username: '.$user->data->user_login."<br />"
			             . 'Nice Name: '.$user->data->user_nicename."<br />"
			             . 'Display Name: '.$user->data->display_name."<br />"
			             . 'Email: '.$user->data->user_email."<br />"
			             . 'URL (website): '.$user->data->user_url."<br />"
			             . 'Registration Date: '.$user->data->user_registered."<br />"
			             . '<li>';
		}
		$listHtml .= '</ul>';

		return $listHtml;
	}

}

// register my-users-list shortcode
add_shortcode('my-users-list', 'my_custom_users_list');

//to test the shortcode, uncomment next line:
/*echo do_shortcode('[my-users-list]');*/

Using the shortcode inside WP editor or do_shortcode function

To use this custom-made shortcode, you can add [my-users-list] in the WordPress editor while editing a post or page (or whatever).

If you want to use this function in PHP code, you can use:

echo do_shortcode('[my-users-list]');

What do you think about "How to Get Users in WordPress (+Shortcode to Print Users in a List)"?

Your rating submit was successfull.

Your rating submit was not successfull.

Menu