How to Get and Display a User Avatar in the WordPress Post Loop

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:

  1. get_the_author_meta('ID')
    Retrieves the author’s ID.
  2. 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).
  3. 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.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more