How to list users using WP_User_Query and shortcodes

How to list users using WP_User_Query and shortcodes

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 '<ul>';
    foreach ($results as $item) {
    ?>
        <li>
            <?php echo get_avatar($item->user_email, 80); ?>
            <a href="<?php echo get_author_posts_url($item->ID); ?>"><?php echo esc_html($item->display_name); ?></a><br />
            <?php echo esc_html($item->user_email); ?><br />
            <?php echo count_user_posts($item->ID); ?> posts
        </li>
    <?php
    }
    echo '</ul>';
    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"]
Leave a Reply

Get our Wordpress
freebies to your inbox