Quick post today. I recently had been working in a site with a CMS powered by WordPress and was asked to list nicely all the full names and emails of all the active users. As I didn’t found a function/solution out of the box thought of sharing it with you.
One thing to keep in mind is that WordPress keeps users data in two separates tables, users and usermeta. The first one stores what I would say its the most relevant information of the user for the system, the username, the email, password, etc. And the second one stores all remaining data, first name, last name, etc. Depending of which plugins you have installed you could have more/different fields. To mix the information of these two tables into one object WordPress provides the
get_userdata(); function, which returns an object that we can use to easily display the information we want. To call this function we need to provide a user ID number, so to list all users with their details we have to first know the IDs of them.
The code to do this is pretty simple and it goes like this:
<ul id="membersList"> <?php /* First we set how we'll want to sort the user list. You could sort them by: ------------------------ * ID - User ID number. * user_login - User Login name. * user_nicename - User Nice name ( nice version of login name ). * user_email - User Email Address. * user_url - User Website URL. * user_registered - User Registration date. */ $szSort = "user_nicename"; /* Now we build the custom query to get the ID of the users. */ $aUsersID = $wpdb->get_col( $wpdb->prepare( "SELECT $wpdb->users.ID FROM $wpdb->users ORDER BY %s ASC" , $szSort )); /* Once we have the IDs we loop through them with a Foreach statement. */ foreach ( $aUsersID as $iUserID ) : /* We use get_userdata() function with each ID. */ $user = get_userdata( $iUserID ); /* Here we finally print the details wanted. Check the description of the database tables linked above to see all the fields you can retrieve. To echo a property simply call it with $user->name_of_the_column. In this example I print the first and last name. */ echo '<li>' . ucwords( strtolower( $user->first_name . ' ' . $user->last_name ) ) . '</li>'; /* The strtolower and ucwords part is to be sure the full names will all be capitalized. */ endforeach; // end the users loop. ?> </ul>
The code itself its pretty explanatory, hope you find the code useful. Cheers!