get_avatar_data()WP 4.2.0

Gets an array of data about the avatar, by the provided email, ID, user object, post object, or comment object.

This function does not check if there is actually an avatar; it simply collects the URL from the gravatar.com service. To check if the email has an avatar, you need to separately process the obtained URL. You should specify 404 in default, then get the URL and try to fetch the image from that URL using get_headers(). If the response returns 404, then there is no avatar for the email.

See also the function get_avatar().

Returns

Array. An array of data for the obtained avatar. The array will contain all the data passed in the $args parameter as well as additional fields:

  • 'found_avatar' - (boolean) true - if the user's avatar was found, false or empty - if not found.

  • 'url' - (string) URL of the found avatar.

The returned parameter 'found_avatar' is always defined when the avatar image was successfully obtained, even if the parameter default=404. 'found_avatar' does not indicate whether the user has a real avatar.

Usage

get_avatar_data( $id_or_email, $args );
$id_or_email(mixed) (required)

Identifier by which the avatar will be determined. It can be:

  • email - [email protected]
  • gravatar md5 hash (md5 hash of the email)
  • user ID - will get the user's avatar by email
  • WP_User object - will get the user's avatar by email
  • WP_Post object - will get the avatar of the post author
  • WP_Comment object - will get the avatar of the commenter
$args(array)

Parameters for the obtained avatar. By default:

Default: null (presets)

  • size(int)
    Height and width of the avatar in pixels.
    Default: 96

  • default(string)
    URL for the default image - if the avatar could not be obtained. Instead of a URL, you can specify the following values:

    • 404 - will return 404 instead of the default image.
    • retro - pixel image 8bit:
    • monsterid - monster:
    • wavatar - cartoon face:
    • indenticon - pattern image:
    • mystery, 'mm' or 'mysterman' - unknown person:
    • blank - transparent GIF image.
    • gravatar_default - Gravatar logo:

    Default: value of the 'avatar_default' option or 'mystery'

  • force_default(boolean)
    Set to true if you always want to show the default image and not show avatars at all.
    Default: false

  • rating(string)
    The maximum allowable rating for the displayed avatar. It can be:

    • G — Suitable for any audience;
    • PG — May contain offensive elements, usually for audiences over 13 years old;
    • R — Intended for adult audiences over 17 years old;
    • X — For even more mature audiences;

    Default: value of the 'avatar_rating' option

  • scheme(string)
    URL scheme to be used. It can be: 'http', 'https', 'login', 'login_post', 'admin', or 'relative'. See the function set_url_scheme() for more details.
    Default: null

  • processed_args(array)
    Additional options to pass. When filtering and returning data from the get_avatar_data() function, these parameters will be added to the returned array.
    Default: null

  • extra_attr(string)
    HTML attributes to add to the IMG element. Not sanitized.
    Default: ''

Examples

1

#1 Get the avatar data of the author of the current post

global $post;
$ava_data = get_avatar_data( $post, "size=52&default=monsterid" );

/*
Array
(
	[size] => 52
	[height] => 52
	[width] => 52
	[default] => monsterid
	[force_default] => 
	[rating] => g
	[scheme] => 
	[processed_args] => 
	[extra_attr] => 
	[found_avatar] => 1
	[url] => http://1.gravatar.com/avatar/155e695ab2251ee3c482c1e3e690683b?s=52&d=monsterid&r=g
)
*/
0

#2 Get the avatar data from the user's email

$ava_data = get_avatar_data( '[email protected]', array(
	'size' => 48,
	'default'=>'identicon',
) );

/*
Array
(
	[size] => 48
	[height] => 48
	[width] => 48
	[default] => identicon
	[force_default] => 
	[rating] => g
	[scheme] => 
	[processed_args] => 
	[extra_attr] => 
	[found_avatar] => 1
	[url] => http://1.gravatar.com/avatar/4b508f04b661ba693130539bd29f5c0d?s=48&d=identicon&r=g
)
*/
0

#3 Get the avatar data of the current user

$ava_data = get_avatar_data( wp_get_current_user(), array(
	'size' => 24,
	'default'=>'wavatar',
) );

/*
Array
(
	[size] => 24
	[height] => 24
	[width] => 24
	[default] => wavatar
	[force_default] => 
	[rating] => g
	[scheme] => 
	[processed_args] => 
	[extra_attr] => 
	[found_avatar] => 1
	[url] => http://1.gravatar.com/avatar/155e695ab2251ee3c482c1e3e690683b?s=24&d=wavatar&r=g
)
*/
0

#4 Transmit additional parameters

$ava_data = get_avatar_data( '[email protected]', array(
	'processed_args' => [ 10, 'foo' ],
	'extra_attr'     => 'style="foo"',
));

print_r( $ava_data );

/*
Array
(
	[size] => 24
	[height] => 24
	[width] => 24
	[default] => mm
	[force_default] => 
	[rating] => x
	[scheme] => 
	[processed_args] => Array
		(
			[0] => 10
			[1] => foo
		)

	[extra_attr] => style="foo"
	[found_avatar] => 1
	[url] => http://1.gravatar.com/avatar/4420889f9734a17a5168dbec7891a4c9?s=24&d=mm&r=x
)
*/

Changelog

Since 4.2.0 Introduced.
Since 6.7.0 Gravatar URLs always use HTTPS.
Since 6.8.0 Gravatar URLs use the SHA-256 hashing algorithm.

get_avatar_data() code WP 6.9.1

function get_avatar_data( $id_or_email, $args = null ) {
	$args = wp_parse_args(
		$args,
		array(
			'size'           => 96,
			'height'         => null,
			'width'          => null,
			'default'        => get_option( 'avatar_default', 'mystery' ),
			'force_default'  => false,
			'rating'         => get_option( 'avatar_rating' ),
			'scheme'         => null,
			'processed_args' => null, // If used, should be a reference.
			'extra_attr'     => '',
		)
	);

	if ( is_numeric( $args['size'] ) ) {
		$args['size'] = absint( $args['size'] );
		if ( ! $args['size'] ) {
			$args['size'] = 96;
		}
	} else {
		$args['size'] = 96;
	}

	if ( is_numeric( $args['height'] ) ) {
		$args['height'] = absint( $args['height'] );
		if ( ! $args['height'] ) {
			$args['height'] = $args['size'];
		}
	} else {
		$args['height'] = $args['size'];
	}

	if ( is_numeric( $args['width'] ) ) {
		$args['width'] = absint( $args['width'] );
		if ( ! $args['width'] ) {
			$args['width'] = $args['size'];
		}
	} else {
		$args['width'] = $args['size'];
	}

	if ( empty( $args['default'] ) ) {
		$args['default'] = get_option( 'avatar_default', 'mystery' );
	}

	switch ( $args['default'] ) {
		case 'mm':
		case 'mystery':
		case 'mysteryman':
			$args['default'] = 'mm';
			break;
		case 'gravatar_default':
			$args['default'] = false;
			break;
	}

	$args['force_default'] = (bool) $args['force_default'];

	$args['rating'] = strtolower( $args['rating'] );

	$args['found_avatar'] = false;

	/**
	 * Filters whether to retrieve the avatar URL early.
	 *
	 * Passing a non-null value in the 'url' member of the return array will
	 * effectively short circuit get_avatar_data(), passing the value through
	 * the {@see 'get_avatar_data'} filter and returning early.
	 *
	 * @since 4.2.0
	 *
	 * @param array $args        Arguments passed to get_avatar_data(), after processing.
	 * @param mixed $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar SHA-256 or MD5 hash,
	 *                           user email, WP_User object, WP_Post object, or WP_Comment object.
	 */
	$args = apply_filters( 'pre_get_avatar_data', $args, $id_or_email );

	if ( isset( $args['url'] ) ) {
		/** This filter is documented in wp-includes/link-template.php */
		return apply_filters( 'get_avatar_data', $args, $id_or_email );
	}

	$email_hash = '';
	$user       = false;
	$email      = false;

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

	// Process the user identifier.
	if ( is_numeric( $id_or_email ) ) {
		$user = get_user_by( 'id', absint( $id_or_email ) );
	} elseif ( is_string( $id_or_email ) ) {
		if ( str_contains( $id_or_email, '@sha256.gravatar.com' ) ) {
			// SHA-256 hash.
			list( $email_hash ) = explode( '@', $id_or_email );
		} elseif ( str_contains( $id_or_email, '@md5.gravatar.com' ) ) {
			// MD5 hash.
			list( $email_hash ) = explode( '@', $id_or_email );
		} else {
			// Email address.
			$email = $id_or_email;
		}
	} elseif ( $id_or_email instanceof WP_User ) {
		// User object.
		$user = $id_or_email;
	} elseif ( $id_or_email instanceof WP_Post ) {
		// Post object.
		$user = get_user_by( 'id', (int) $id_or_email->post_author );
	} elseif ( $id_or_email instanceof WP_Comment ) {
		if ( ! is_avatar_comment_type( get_comment_type( $id_or_email ) ) ) {
			$args['url'] = false;
			/** This filter is documented in wp-includes/link-template.php */
			return apply_filters( 'get_avatar_data', $args, $id_or_email );
		}

		if ( ! empty( $id_or_email->user_id ) ) {
			$user = get_user_by( 'id', (int) $id_or_email->user_id );
		}
		if ( ( ! $user || is_wp_error( $user ) ) && ! empty( $id_or_email->comment_author_email ) ) {
			$email = $id_or_email->comment_author_email;
		}
	}

	if ( ! $email_hash ) {
		if ( $user ) {
			$email = $user->user_email;
		}

		if ( $email ) {
			$email_hash = hash( 'sha256', strtolower( trim( $email ) ) );
		}
	}

	if ( $email_hash ) {
		$args['found_avatar'] = true;
	}

	$url_args = array(
		's' => $args['size'],
		'd' => $args['default'],
		'f' => $args['force_default'] ? 'y' : false,
		'r' => $args['rating'],
	);

	// Handle additional parameters for the 'initials' avatar type.
	if ( 'initials' === $args['default'] ) {
		$name = '';

		if ( $user ) {
			if ( '' !== $user->display_name ) {
				$name = $user->display_name;
			} elseif ( '' !== $user->first_name && '' !== $user->last_name ) {
				$name = sprintf(
					/* translators: 1: User's first name, 2: Last name. */
					_x( '%1$s %2$s', 'Display name based on first name and last name' ),
					$user->first_name,
					$user->last_name
				);
			} else {
				$name = $user->user_login;
			}
		} elseif ( $id_or_email instanceof WP_Comment ) {
			$name = $id_or_email->comment_author;
		} elseif ( is_string( $id_or_email ) && false !== strpos( $id_or_email, '@' ) ) {
			$name = str_replace( array( '.', '_', '-' ), ' ', substr( $id_or_email, 0, strpos( $id_or_email, '@' ) ) );
		}

		if ( '' !== $name ) {
			if ( ! str_contains( $name, ' ' ) || preg_match( '/\p{Han}|\p{Hiragana}|\p{Katakana}|\p{Hangul}/u', $name ) ) {
				$initials = mb_substr( $name, 0, min( 2, mb_strlen( $name, 'UTF-8' ) ), 'UTF-8' );
			} else {
				$first    = mb_substr( $name, 0, 1, 'UTF-8' );
				$last     = mb_substr( $name, strrpos( $name, ' ' ) + 1, 1, 'UTF-8' );
				$initials = $first . $last;
			}

			$url_args['initials'] = $initials;
		}
	}

	/*
	 * Gravatars are always served over HTTPS.
	 *
	 * The Gravatar website redirects HTTP requests to HTTPS URLs so always
	 * use the HTTPS scheme to avoid unnecessary redirects.
	 */
	$url = 'https://secure.gravatar.com/avatar/' . $email_hash;

	$url = add_query_arg(
		rawurlencode_deep( array_filter( $url_args ) ),
		$url
	);

	/**
	 * Filters the avatar URL.
	 *
	 * @since 4.2.0
	 *
	 * @param string $url         The URL of the avatar.
	 * @param mixed  $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar SHA-256 or MD5 hash,
	 *                            user email, WP_User object, WP_Post object, or WP_Comment object.
	 * @param array  $args        Arguments passed to get_avatar_data(), after processing.
	 */
	$args['url'] = apply_filters( 'get_avatar_url', $url, $id_or_email, $args );

	/**
	 * Filters the avatar data.
	 *
	 * @since 4.2.0
	 *
	 * @param array $args        Arguments passed to get_avatar_data(), after processing.
	 * @param mixed $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar SHA-256 or MD5 hash,
	 *                           user email, WP_User object, WP_Post object, or WP_Comment object.
	 */
	return apply_filters( 'get_avatar_data', $args, $id_or_email );
}