Using WordPress ‘get_avatar()’ PHP function

The get_avatar() WordPress PHP function retrieves the avatar <img> tag for a user, email address, MD5 hash, comment, or post.

Usage

echo get_avatar($id_or_email, $size = 96, $default_value = '', $alt = '', $args = null);

Parameters

  • $id_or_email (mixed, required): The Gravatar to retrieve. Accepts a user_id, gravatar md5 hash, user email, WP_User object, WP_Post object, or WP_Comment object.
  • $size (int, optional): Height and width of the avatar image file in pixels. Default is 96.
  • $default_value (string, optional): URL for the default image or a default type. Default is the value of the ‘avatar_default’ option, with a fallback of ‘mystery’.
  • $alt (string, optional): Alternative text to use in the <img> tag. Default is an empty string.
  • $args (array, optional): Extra arguments to retrieve the avatar.

More information

See WordPress Developer Resources: get_avatar()

Examples

Display an author’s avatar in The Loop

This code retrieves and displays the avatar of a post’s author using their user ID.

echo get_avatar(get_the_author_meta('ID'), 32);

Display a comment author’s avatar

This code retrieves and displays the avatar of a comment author.

echo get_avatar($comment, 32);

Display avatar for a random email address

This code retrieves and displays the avatar for a given email address.

echo get_avatar('[email protected]', 32);

Add a custom class to the avatar <img> tag

This code retrieves and displays the avatar with a custom class added to the <img> element.

echo get_avatar(get_the_author_meta('ID'), 60, '', '', array('class' => 'wt-author-img'));

Display avatar with a custom default image

This code retrieves and displays the avatar with a custom default image URL.

echo get_avatar(get_the_author_meta('ID'), 48, 'https://example.com/default-avatar.png');