How to list users using WP_User_Query and shortcodes

Sometimes we need to list our blog authors (in a dynamic way) on “About” pages and this can be done by using a shortcode and WP_User_Query built-in class.

If you need to dynamically list the blog authors on “About” pages, you can do this by using a shortcode and WP_User_Query built-in class. Let’s start with the shortcode code:

function wcr_list_users($atts) {
    // I don't use shortcode_atts because I want to have a dynamic number of attributes
    $query = new WP_User_Query($atts);
    $results = $query->get_results();

    // no results
    if (empty($results)) {
        return;
    }
	
    // when we have results
    ob_start();
    echo '
    '; foreach ($results as $item) { ?>
  • user_email, 80); ?> display_name); ?>
    user_email); ?>
    ID); ?> posts
  • '; return ob_get_clean(); } add_shortcode('list_users', 'wcr_list_users');

Here are a few se case scenarios:

// list 5 users with contributor role, order by name
[list_users number="5" role="contributor" orderby="name"]
// list users by number of posts - DESC
[list_users orderby="post_count" order="DESC"]
// list 10 users by searching after a keyword
[list_users number="10" search="michael"]

One comment

Leave a Reply

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