How to make a user profiles section with the user avatar and custom meta fields with WP_User_Query?
WP_User_Query doesn’t give direct access to the user avatar, so how to show the avatar?
Regular profile fields are easy to reference from the codex.
But what about custom meta fields?
Displaying the avatar and other user meta with WP_User_Query isn’t quite straight forward. Some user profile data is returned by default, but user meta fields and avatar takes a little more effort.
Here is a code snippit to add to functions.php that will output a Meet the Team section, or User Profiles list or Contributors Section:
function author_profiles() {
$args = array(
'meta_key' => 'display-order', //This is a custom field added to user contact info
'orderby' => 'meta_value_num', //Use a number in the custom field for orderby
'roll' => 'Author', //Authors Only
'fields' => 'all_with_meta', //Get all meta fields
);
$user_query = new WP_User_Query( $args );
// User Loop
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
?>
<!-- // A direct user_query result -->
<h2><?php echo $user->display_name ?>
</h2>
<div class="user-avatar">
<!-- // Use the user_query ID to get the avatar -->
<?php echo get_avatar($user->ID) ?>
</div>
<!-- //A custom user meta field. Uses: get() -->
<a href="tel:+1<?php echo $user->get('office-phone') ?>">
<?php echo $user->get('office-phone') ?>
</a>
Email: <a href="mailto:<?php echo $user->user_email ?>">
<?php echo $user->user_email ?>
</a>
<!-- link to the author's archive page -->
<a href="<?php echo get_site_url() . '/author/' . $user->user_nicename?>">
<?php echo $user->first_name ?>'s Bio & Blog
</a>
<?php
}
} else {
echo 'No users found.';
}
}
Output the function in the loop of a custom template:
echo '<div>' . author_profiles() .'</div>';