To get and display a user’s avatar in the WordPress post loop, you can use the get_avatar()
function. This function returns the HTML code for the user’s avatar image.
Code Example:
<?php
if (have_posts()) :
while (have_posts()) : the_post();
// Get the current post author's ID
$author_id = get_the_author_meta('ID');
// Get the author's avatar
$avatar = get_avatar($author_id, 96); // 96 is the size of the avatar in pixels
// Display the avatar and other information
echo '<div class="post-author">';
echo $avatar; // Output the avatar
echo '<p>Author: ' . get_the_author() . '</p>';
echo '</div>';
endwhile;
endif;
?>
Explanation:
get_the_author_meta('ID')
Retrieves the author’s ID.get_avatar($author_id, $size)
Returns the HTML code for the user’s avatar.
Parameters:$author_id
— The user’s ID.$size
— The size of the avatar (default is 96 pixels).
get_the_author()
Returns the name of the post’s author.
Adding Styles
You can style the avatar and author information using CSS. For example:
.post-author {
display: flex;
align-items: center;
}
.post-author img {
border-radius: 50%;
margin-right: 10px;
}
Display in Post Cards
If you want to use this code in template files (e.g., archive.php
or single.php
), place it in the appropriate location within the loop.