WordPress at Your Fingertips

get_avatar()WP 2.5.0

Retrieve the <img> tag with the avatar of a user who is authorized or provided an email address when commenting. Most commonly used in the comments section.

Is used in the Comment Loop or the first parameter should be specified!

This function is pluggable, however, plugin authors wishing to change the output can use the get_avatar filter instead.

Pluggable function — this function can be replaced from a plugin. It means that this function is defined (works) only after all plugins are loaded (included), but before this moment this function has not defined. Therefore, you cannot call this and all functions depended on this function directly from a plugin code. They need to be called on plugins_loaded hook or later, for example on init hook.

Function replacement (override) — in must-use or regular plugin you can create a function with the same name, then it will replace this function.

1 time — 0.000196 sec (fast) | 50000 times — 4.98 sec (fast) | PHP 7.1.0, WP 4.7.1
Hooks from the function

Return

String|false. <img> tag for the user's avatar. False on failure. If the user doesn't have an avatar — will be returned the default avatar — not a false.

Usage

get_avatar( $id_or_email, $size, $default, $alt, $args );
$id_or_email(mixed) (required)

User ID or email to retrieve the avatar for. Also accepts: WP_User, WP_Post, WP_Comment objects or gravatar md5 hash.

In most cases, the global variable $comment is passed to this parameter. If it doesn't work out (you get an error), then you can write a commenter's email to this variable like so:

get_the_author_meta('[email protected]');
$size(int)
Height and width of the avatar image (in pixels).
Default: 96
$default(string)

URL for the default image when the user doesn't have a gravatar.
Also accepts

  • 404 - return a 404 instead of a default image.
  • retro - 8bit pixel picture:
  • monsterid - monster:
  • wavatar - cartoon face:
  • indenticon - the "quilt":
  • mystery, 'mm' or 'mysterman' - The Oyster Man:
  • blank - transparent GIF.
  • gravatar_default - the Gravatar logo:

Default: value of the 'avatar_default' option, with a fallback of 'mystery'

$alt(string)
Text for the <img> alt attribute.
Default: ''
$args(array)

Extra arguments to retrieve the avatar.

  • $height(int)
    Display height of the avatar in pixels.
    Default: $size

  • $width(int)
    Display width of the avatar in pixels.
    Default: $size

  • $force_default(true/false)
    Whether to always show the default image, never the Gravatar.
    Default: false

  • $rating(string)
    What rating to display avatars up to. Accepts 'G', 'PG', 'R', 'X', and are judged in that order.
    Default: value of the 'avatar_rating' option

  • $scheme(string)
    URL scheme to use. See set_url_scheme() for accepted values.
    Default: null

  • $class(array/string)
    Array or string of additional classes to add to the <img> element.
    Default: null

  • $force_display(true/false)
    Whether to always show the avatar - ignores the show_avatars option.
    Default: false

  • $extra_attr(string)
    HTML attributes to insert in the IMG element. Is not sanitized.
    Default: ''

Default: null

Examples

1

#1 Add an additional default avatar option

The code below adds an additional Default Avatar option to the Discussion settings page. Selected avatar is saved in get_option('avatar_default') option.

# Adds a new default avatar
# The avatar file is 'def-avatar.jpg' in the theme's 'img' directory
add_filter( 'avatar_defaults', 'add_default_avatar_option' );
function add_default_avatar_option( $avatars ){
	$url = get_stylesheet_directory_uri() . '/img/def-avatar.jpg';
	$avatars[ $url ] = 'A website avatar';
	return $avatars;
}

In the result, we will get such option:

0

#2 Show the avatar of the current post author

<?php echo get_avatar( get_the_author_meta('user_email'), 32 ); ?>
0

#3 Add a style attribute to the avatar

<?php echo get_avatar( $current_user->user_email, 30, '', '', array('class'=>'pull-left', 'extra_attr'=>'style="margin: -4px 7px;"') ); ?>

output:

<img alt="" src="http://1.gravatar.com/avatar/155e695ab2987ee3c482c1e3e690683b?s=30&d=mm&r=g" 
	class="avatar avatar-30 photo pull-left" 
	height="30" width="30" 
	style="margin: -4px 7px;"
>
0

#4 Setup a default avatar

If in the previous example, to choose the default avatar, we need to go to the Descussion settings page and then choose a new avatar, here we can do it automatically via a hook.

The below code setups a default avatar for all avatar functions: get_avatar_url() and get_avatar_data(). But if default avatar is specified in the arguments of these functions, it will be chosen over the avatar specified by the hook (so the functions will have a higher priority).

## Setups a default avatar
## The avatar file is 'def-avatar.jpg' in the theme's 'img' directory
add_filter( 'pre_get_avatar_data', 'replace_default_avatar' );
function replace_default_avatar( $args ){
	// Discussion settings page where the default avatar can be chosen...
	// if( is_admin() && get_current_screen()->base === 'options-discussion' ) return $args;

	static $defava; if( $defava === null ) $defava = get_option( 'avatar_default', 'mystery' ); // ускоримся

	// To give the avatar functions priority over this hook. 
	// So if the developer has specified a default avatar in the functions, it won't be reset by this hook.
	if( ! $args['default'] || $defava == $args['default'] ){
		$args['default'] = get_stylesheet_directory_uri() . '/img/def-avatar.jpg';
	}

	return $args;
}
-7

#5 Show the avatar of the current commenter

<?php echo get_avatar( $comment, 32 ); ?>

Output:

<img alt='' src='http://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s=32' class='avatar avatar-32 photo avatar-default' height='32' width='32' />

Changelog

Since 2.5.0 Introduced.
Since 4.2.0 Added the optional $args parameter.
Since 5.5.0 Added the loading argument.
Since 6.1.0 Added the decoding argument.
Since 6.3.0 Added the fetchpriority argument.

get_avatar() code WP 6.5.2

function get_avatar( $id_or_email, $size = 96, $default_value = '', $alt = '', $args = null ) {
	$defaults = array(
		// get_avatar_data() args.
		'size'          => 96,
		'height'        => null,
		'width'         => null,
		'default'       => get_option( 'avatar_default', 'mystery' ),
		'force_default' => false,
		'rating'        => get_option( 'avatar_rating' ),
		'scheme'        => null,
		'alt'           => '',
		'class'         => null,
		'force_display' => false,
		'loading'       => null,
		'fetchpriority' => null,
		'decoding'      => null,
		'extra_attr'    => '',
	);

	if ( empty( $args ) ) {
		$args = array();
	}

	$args['size']    = (int) $size;
	$args['default'] = $default_value;
	$args['alt']     = $alt;

	$args = wp_parse_args( $args, $defaults );

	if ( empty( $args['height'] ) ) {
		$args['height'] = $args['size'];
	}
	if ( empty( $args['width'] ) ) {
		$args['width'] = $args['size'];
	}

	// Update args with loading optimized attributes.
	$loading_optimization_attr = wp_get_loading_optimization_attributes( 'img', $args, 'get_avatar' );

	$args = array_merge( $args, $loading_optimization_attr );

	if ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) {
		$id_or_email = get_comment( $id_or_email );
	}

	/**
	 * Allows the HTML for a user's avatar to be returned early.
	 *
	 * Returning a non-null value will effectively short-circuit get_avatar(), passing
	 * the value through the {@see 'get_avatar'} filter and returning early.
	 *
	 * @since 4.2.0
	 *
	 * @param string|null $avatar      HTML for the user's avatar. Default null.
	 * @param mixed       $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash,
	 *                                 user email, WP_User object, WP_Post object, or WP_Comment object.
	 * @param array       $args        Arguments passed to get_avatar_url(), after processing.
	 */
	$avatar = apply_filters( 'pre_get_avatar', null, $id_or_email, $args );

	if ( ! is_null( $avatar ) ) {
		/** This filter is documented in wp-includes/pluggable.php */
		return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
	}

	if ( ! $args['force_display'] && ! get_option( 'show_avatars' ) ) {
		return false;
	}

	$url2x = get_avatar_url( $id_or_email, array_merge( $args, array( 'size' => $args['size'] * 2 ) ) );

	$args = get_avatar_data( $id_or_email, $args );

	$url = $args['url'];

	if ( ! $url || is_wp_error( $url ) ) {
		return false;
	}

	$class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' );

	if ( ! $args['found_avatar'] || $args['force_default'] ) {
		$class[] = 'avatar-default';
	}

	if ( $args['class'] ) {
		if ( is_array( $args['class'] ) ) {
			$class = array_merge( $class, $args['class'] );
		} else {
			$class[] = $args['class'];
		}
	}

	// Add `loading`, `fetchpriority`, and `decoding` attributes.
	$extra_attr = $args['extra_attr'];

	if ( in_array( $args['loading'], array( 'lazy', 'eager' ), true )
		&& ! preg_match( '/\bloading\s*=/', $extra_attr )
	) {
		if ( ! empty( $extra_attr ) ) {
			$extra_attr .= ' ';
		}

		$extra_attr .= "loading='{$args['loading']}'";
	}

	if ( in_array( $args['fetchpriority'], array( 'high', 'low', 'auto' ), true )
		&& ! preg_match( '/\bfetchpriority\s*=/', $extra_attr )
	) {
		if ( ! empty( $extra_attr ) ) {
			$extra_attr .= ' ';
		}

		$extra_attr .= "fetchpriority='{$args['fetchpriority']}'";
	}

	if ( in_array( $args['decoding'], array( 'async', 'sync', 'auto' ), true )
		&& ! preg_match( '/\bdecoding\s*=/', $extra_attr )
	) {
		if ( ! empty( $extra_attr ) ) {
			$extra_attr .= ' ';
		}

		$extra_attr .= "decoding='{$args['decoding']}'";
	}

	$avatar = sprintf(
		"<img alt='%s' src='%s' srcset='%s' class='%s' height='%d' width='%d' %s/>",
		esc_attr( $args['alt'] ),
		esc_url( $url ),
		esc_url( $url2x ) . ' 2x',
		esc_attr( implode( ' ', $class ) ),
		(int) $args['height'],
		(int) $args['width'],
		$extra_attr
	);

	/**
	 * Filters the HTML for a user's avatar.
	 *
	 * @since 2.5.0
	 * @since 4.2.0 Added the `$args` parameter.
	 *
	 * @param string $avatar        HTML for the user's avatar.
	 * @param mixed  $id_or_email   The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash,
	 *                              user email, WP_User object, WP_Post object, or WP_Comment object.
	 * @param int    $size          Height and width of the avatar in pixels.
	 * @param string $default_value URL for the default image or a default type. Accepts:
	 *                              - '404' (return a 404 instead of a default image)
	 *                              - 'retro' (a 8-bit arcade-style pixelated face)
	 *                              - 'robohash' (a robot)
	 *                              - 'monsterid' (a monster)
	 *                              - 'wavatar' (a cartoon face)
	 *                              - 'identicon' (the "quilt", a geometric pattern)
	 *                              - 'mystery', 'mm', or 'mysteryman' (The Oyster Man)
	 *                              - 'blank' (transparent GIF)
	 *                              - 'gravatar_default' (the Gravatar logo)
	 * @param string $alt           Alternative text to use in the avatar image tag.
	 * @param array  $args          Arguments passed to get_avatar_data(), after processing.
	 */
	return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
}
1 comment
    Log In