WordPress at a glance

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.

This is a pluggable function, and it can be replaced by 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 a plugin you can create a function with the same name, then it replace this function.

✈ 1 time = 0.000196s = fast | 50000 times = 4.98s = fast | PHP 7.1.0, WP 4.7.1
Hooks from the function
Return

false/String. <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@gmail.com');
$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 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' />

#2 Show the avatar of the current post author

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

#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;"
>

#4 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:

#5 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;
}

Changelog

Since 2.5.0 Introduced.
Since 4.2.0 Optional $args parameter added.

Code of get avatar: wp-includes/pluggable.php WP 5.2.2

<?php
function get_avatar( $id_or_email, $size = 96, $default = '', $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,
		'extra_attr'    => '',
	);

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

	$args['size']    = (int) $size;
	$args['default'] = $default;
	$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'];
	}

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

	/**
	 * Filters whether to retrieve the avatar URL early.
	 *
	 * Passing 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 $avatar      HTML for the user's avatar. Default null.
	 * @param mixed  $id_or_email The Gravatar 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'];
		}
	}

	$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( join( ' ', $class ) ),
		(int) $args['height'],
		(int) $args['width'],
		$args['extra_attr']
	);

	/**
	 * Filters the avatar to retrieve.
	 *
	 * @since 2.5.0
	 * @since 4.2.0 The `$args` parameter was added.
	 *
	 * @param string $avatar      &lt;img&gt; tag for the user's avatar.
	 * @param mixed  $id_or_email The Gravatar to retrieve. Accepts a user_id, gravatar md5 hash,
	 *                            user email, WP_User object, WP_Post object, or WP_Comment object.
	 * @param int    $size        Square avatar width and height in pixels to retrieve.
	 * @param string $default     URL for the default image or a default type. Accepts '404', 'retro', 'monsterid',
	 *                            'wavatar', 'indenticon','mystery' (or 'mm', or 'mysteryman'), 'blank', or 'gravatar_default'.
	 *                            Default is the value of the 'avatar_default' option, with a fallback of 'mystery'.
	 * @param string $alt         Alternative text to use in the avatar image tag. Default empty.
	 * @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 );
}

Related Functions

From tag: avatar

More from category: Comments

No comments
    Hello, !     Log In . Register