How to list users by custom field?

I have a custom user field in the standard database, called “company”.
I want to output on to a page the usermeta info only of users whose “company” matches “Widgets Inc” …

How do I do that?

Read More

What I think I’d like to be able to do is avoid putting this in a page template and instead create a shortcode to list user info, with functionality to limit by field attribute – ie. {listusers company=”Widgets Inc”}

But I don’t know how to do that.

Thanks

Related posts

Leave a Reply

1 comment

  1. Try this one

    add_shortcode( 'list-company-users', 'company_users_shortcode' );
    function company_users_shortcode($atts)
    {
        ob_start();
        $query = array('meta_key' => 'company', 'meta_value' => 'Widgets Inc');
    
        $user_query = new WP_User_Query($query);
    
    // User Loop
        if (!empty($user_query->results)) {
            foreach ($user_query->results as $user) {
                echo '<p>' . $user->display_name . '</p>';
            }
        } else {
            echo 'No users found.';
        }
        $myvariable = ob_get_clean();
        return $myvariable;
    }
    

    And here is your short code [list-company-users]

    To define to use parameters in short code you can do like this

    [list-company-users company="Widgets Inc"]
    

    Now you have to extract the values passed in shortcode via shortcode_atts()

     extract(shortcode_atts(array("company" => 0), $atts));
    
    
    function company_users_shortcode($atts)
    {
        ob_start();
        extract(shortcode_atts(array("company" => 0), $atts));
        $query = array('meta_key' => 'company', 'meta_value' => $atts[company]);
    
        $user_query = new WP_User_Query($query);
    
    // User Loop
        if (!empty($user_query->results)) {
            foreach ($user_query->results as $user) {
                echo '<p>' . $user->display_name . '</p>';
            }
        } else {
            echo 'No users found.';
        }
        $myvariable = ob_get_clean();
        return $myvariable;
    }
    

    References

    Create a Shortcode

    WP_User_Query