bp_core_fetch_avatar( array|string $args = '' )

Get an avatar for a BuddyPress object.

Description

Supports avatars for users, groups, and blogs by default, but can be extended to support custom components as well.

This function gives precedence to locally-uploaded avatars. When a local avatar is not found, Gravatar is queried. To disable Gravatar fallbacks locally: add_filter( ‘bp_core_fetch_avatar_no_grav’, ‘__return_true’ );

Parameters

$args

(array|string) (Optional) An array of arguments. All arguments are technically optional; some will, if not provided, be auto-detected by bp_core_fetch_avatar(). This auto-detection is described more below, when discussing specific arguments.

  • 'item_id'
    (int|bool) The numeric ID of the item for which you're requesting an avatar (eg, a user ID). If no 'item_id' is present, the function attempts to infer an ID from the 'object' + the current context: if 'object' is 'user' and the current page is a user page, 'item_id' will default to the displayed user ID; if 'group' and on a group page, to the current group ID; if 'blog', to the current blog's ID. If no 'item_id' can be determined in this way, the function returns false. Default: false.
  • 'object'
    (string) The kind of object for which you're getting an avatar. BuddyPress natively supports three options: 'user', 'group', 'blog'; a plugin may register more. Default: 'user'.
  • 'type'
    (string) When a new avatar is uploaded to BP, 'thumb' and 'full' versions are saved. This parameter specifies whether you'd like the 'full' or smaller 'thumb' avatar. Default: 'thumb'.
  • 'avatar_dir'
    (string|bool) The name of the subdirectory where the requested avatar should be found. If no value is passed, 'avatar_dir' is inferred from 'object': 'user' becomes 'avatars', 'group' becomes 'group-avatars', 'blog' becomes 'blog-avatars'. Remember that this string denotes a subdirectory of BP's main avatar directory (usually based on wp_upload_dir()); it's a string like 'group-avatars' rather than the full directory path. Generally, it'll only be necessary to override the default value if storing avatars in a non-default location. Defaults to false (auto-detected).
  • 'width'
    (int|bool) Requested avatar width. The unit is px. This value is used to build the 'width' attribute for the <img> element. If no value is passed, BP uses the global avatar width for this avatar type. Default: false (auto-detected).
  • 'height'
    (int|bool) Requested avatar height. The unit is px. This value is used to build the 'height' attribute for the <img> element. If no value is passed, BP uses the global avatar height for this avatar type. Default: false (auto-detected).
  • 'class'
    (string) The CSS class for the <img> element. Note that BP uses the 'avatar' class fairly extensively in its default styling, so if you plan to pass a custom value, consider appending it to 'avatar' (eg 'avatar foo') rather than replacing it altogether. Default: 'avatar'.
  • 'css_id'
    (string|bool) The CSS id for the <img> element. Default: false.
  • 'title'
    (string) The title attribute for the <img> element. Default: false.
  • 'alt'
    (string) The alt attribute for the <img> element. In BP, this value is generally passed by the wrapper functions, where the data necessary for concatenating the string is at hand; see bp_get_activity_avatar() for an example. Default: ''.
  • 'email'
    (string|bool) An email to use in Gravatar queries. Unless otherwise configured, BP uses Gravatar as a fallback for avatars that are not provided locally. Gravatar's API requires using a hash of the user's email address; this argument provides it. If not provided, the function will infer it: for users, by getting the user's email from the database, for groups/blogs, by concatenating "{$item_id}-{$object}@{bp_get_root_domain()}". The user query adds overhead, so it's recommended that wrapper functions provide a value for 'email' when querying user IDs. Default: false.
  • 'no_grav'
    (bool) Whether to disable the default Gravatar fallback. By default, BP will fall back on Gravatar when it cannot find a local avatar. In some cases, this may be undesirable, in which case 'no_grav' should be set to true. To disable Gravatar fallbacks globally, see the 'bp_core_fetch_avatar_no_grav' filter. Default: true for groups, otherwise false.
  • 'html'
    (bool) Whether to return an <img> HTML element, vs a raw URL to an avatar. If false, <img>-specific arguments (like 'css_id') will be ignored. Default: true.
  • 'extra_attr'
    (string) HTML attributes to insert in the IMG element. Not sanitized. Default: ''.
  • 'scheme'
    (string) URL scheme to use. See set_url_scheme() for accepted values. Default null.
  • 'rating'
    (string) What rating to display Gravatars for. Accepts 'G', 'PG', 'R', 'X'. Default is the value of the 'avatar_rating' option.
  • 'force_default'
    (bool) Used when creating the Gravatar URL. Whether to force the default image regardless if the Gravatar exists. Default: false.

Default value: ''

Return

(string) Formatted HTML <img> element, or raw avatar URL based on $html arg.

Source

File: bp-core/bp-core-avatars.php

function bp_core_fetch_avatar( $args = '' ) {
	$bp = buddypress();

	// If avatars are disabled for the root site, obey that request and bail.
	if ( ! $bp->avatar->show_avatars ) {
		return;
	}

	global $current_blog;

	// Set the default variables array and parse it against incoming $args array.
	$params = wp_parse_args( $args, array(
		'item_id'       => false,
		'object'        => 'user',
		'type'          => 'thumb',
		'avatar_dir'    => false,
		'width'         => false,
		'height'        => false,
		'class'         => 'avatar',
		'css_id'        => false,
		'alt'           => '',
		'email'         => false,
		'no_grav'       => null,
		'html'          => true,
		'title'         => '',
		'extra_attr'    => '',
		'scheme'        => null,
		'rating'        => get_option( 'avatar_rating' ),
		'force_default' => false,
	) );

	/* Set item_id ***********************************************************/

	if ( empty( $params['item_id'] ) ) {

		switch ( $params['object'] ) {

			case 'blog'  :
				$params['item_id'] = $current_blog->id;
				break;

			case 'group' :
				if ( bp_is_active( 'groups' ) ) {
					$params['item_id'] = $bp->groups->current_group->id;
				} else {
					$params['item_id'] = false;
				}

				break;

			case 'user'  :
			default      :
				$params['item_id'] = bp_displayed_user_id();
				break;
		}

		/**
		 * Filters the ID of the item being requested.
		 *
		 * @since BuddyPress 1.1.0
		 *
		 * @param string $value  ID of avatar item being requested.
		 * @param string $value  Avatar type being requested.
		 * @param array  $params Array of parameters for the request.
		 */
		$params['item_id'] = apply_filters( 'bp_core_avatar_item_id', $params['item_id'], $params['object'], $params );

		if ( empty( $params['item_id'] ) ) {
			return false;
		}
	}

	/* Set avatar_dir ********************************************************/

	if ( empty( $params['avatar_dir'] ) ) {

		switch ( $params['object'] ) {

			case 'blog'  :
				$params['avatar_dir'] = 'blog-avatars';
				break;

			case 'group' :
				if ( bp_is_active( 'groups' ) ) {
					$params['avatar_dir'] = 'group-avatars';
				} else {
					$params['avatar_dir'] = false;
				}

				break;

			case 'user'  :
			default      :
				$params['avatar_dir'] = 'avatars';
				break;
		}

		/**
		 * Filters the avatar directory to use.
		 *
		 * @since BuddyPress 1.1.0
		 *
		 * @param string $value  Name of the subdirectory where the requested avatar should be found.
		 * @param string $value  Avatar type being requested.
		 * @param array  $params Array of parameters for the request.
		 */
		$params['avatar_dir'] = apply_filters( 'bp_core_avatar_dir', $params['avatar_dir'], $params['object'], $params );

		if ( empty( $params['avatar_dir'] ) ) {
			return false;
		}
	}

	/* <img> alt *************************************************************/

	if ( false !== strpos( $params['alt'], '%s' ) || false !== strpos( $params['alt'], '%1$s' ) ) {

		switch ( $params['object'] ) {

			case 'blog'  :
				$item_name = get_blog_option( $params['item_id'], 'blogname' );
				break;

			case 'group' :
				$item_name = bp_get_group_name( groups_get_group( $params['item_id'] ) );
				break;

			case 'user'  :
			default :
				$item_name = bp_core_get_user_displayname( $params['item_id'] );
				break;
		}

		/**
		 * Filters the alt attribute value to be applied to avatar.
		 *
		 * @since BuddyPress 1.5.0
		 *
		 * @param string $value  alt to be applied to avatar.
		 * @param string $value  ID of avatar item being requested.
		 * @param string $value  Avatar type being requested.
		 * @param array  $params Array of parameters for the request.
		 */
		$item_name = apply_filters( 'bp_core_avatar_alt', $item_name, $params['item_id'], $params['object'], $params );
		$params['alt'] = sprintf( $params['alt'], $item_name );
	}

	/* Sanity Checks *********************************************************/

	// Get a fallback for the 'alt' parameter, create html output.
	if ( empty( $params['alt'] ) ) {
		$params['alt'] = __( 'Profile Photo', 'buddyboss' );
	}
	$html_alt = ' alt="' . esc_attr( $params['alt'] ) . '"';

	// Filter image title and create html string.
	$html_title = '';

	/**
	 * Filters the title attribute value to be applied to avatar.
	 *
	 * @since BuddyPress 1.5.0
	 *
	 * @param string $value  Title to be applied to avatar.
	 * @param string $value  ID of avatar item being requested.
	 * @param string $value  Avatar type being requested.
	 * @param array  $params Array of parameters for the request.
	 */
	$params['title'] = apply_filters( 'bp_core_avatar_title', $params['title'], $params['item_id'], $params['object'], $params );

	if ( ! empty( $params['title'] ) ) {
		$html_title = ' title="' . esc_attr( $params['title'] ) . '"';
	}

	// Extra attributes.
	$extra_attr = ! empty( $args['extra_attr'] ) ? ' ' . $args['extra_attr'] : '';

	// Set CSS ID and create html string.
	$html_css_id = '';

	/**
	 * Filters the ID attribute to be applied to avatar.
	 *
	 * @since BuddyPress 2.2.0
	 *
	 * @param string $value  ID to be applied to avatar.
	 * @param string $value  ID of avatar item being requested.
	 * @param string $value  Avatar type being requested.
	 * @param array  $params Array of parameters for the request.
	 */
	$params['css_id'] = apply_filters( 'bp_core_css_id', $params['css_id'], $params['item_id'], $params['object'], $params );

	if ( ! empty( $params['css_id'] ) ) {
		$html_css_id = ' id="' . esc_attr( $params['css_id'] ) . '"';
	}

	// Set image width.
	if ( false !== $params['width'] ) {
		// Width has been specified. No modification necessary.
	} elseif ( 'thumb' == $params['type'] ) {
		$params['width'] = bp_core_avatar_thumb_width();
	} else {
		$params['width'] = bp_core_avatar_full_width();
	}
	$html_width = ' width="' . $params['width'] . '"';

	// Set image height.
	if ( false !== $params['height'] ) {
		// Height has been specified. No modification necessary.
	} elseif ( 'thumb' == $params['type'] ) {
		$params['height'] = bp_core_avatar_thumb_height();
	} else {
		$params['height'] = bp_core_avatar_full_height();
	}
	$html_height = ' height="' . $params['height'] . '"';

	/**
	 * Filters the classes to be applied to the avatar.
	 *
	 * @since BuddyPress 1.6.0
	 *
	 * @param array|string $value  Class(es) to be applied to the avatar.
	 * @param string       $value  ID of the avatar item being requested.
	 * @param string       $value  Avatar type being requested.
	 * @param array        $params Array of parameters for the request.
	 */
	$params['class'] = apply_filters( 'bp_core_avatar_class', $params['class'], $params['item_id'], $params['object'], $params );

	// Use an alias to leave the param unchanged.
	$avatar_classes = $params['class'];
	if ( ! is_array( $avatar_classes ) ) {
		$avatar_classes = explode( ' ', $avatar_classes );
	}

	// Merge classes.
	$avatar_classes = array_merge( $avatar_classes, array(
		$params['object'] . '-' . $params['item_id'] . '-avatar',
		'avatar-' . $params['width'],
	) );

	// Sanitize each class.
	$avatar_classes = array_map( 'sanitize_html_class', $avatar_classes );

	// Populate the class attribute.
	$html_class = ' class="' . join( ' ', $avatar_classes ) . ' photo"';

	// Set img URL and DIR based on prepopulated constants.
	$avatar_loc        = new stdClass();
	$avatar_loc->path  = trailingslashit( bp_core_avatar_upload_path() );
	$avatar_loc->url   = trailingslashit( bp_core_avatar_url() );

	$avatar_loc->dir   = trailingslashit( $params['avatar_dir'] );

	/**
	 * Filters the avatar folder directory URL.
	 *
	 * @since BuddyPress 1.1.0
	 *
	 * @param string $value Path to the avatar folder URL.
	 * @param int    $value ID of the avatar item being requested.
	 * @param string $value Avatar type being requested.
	 * @param string $value Subdirectory where the requested avatar should be found.
	 */
	$avatar_folder_url = apply_filters( 'bp_core_avatar_folder_url', ( $avatar_loc->url  . $avatar_loc->dir . $params['item_id'] ), $params['item_id'], $params['object'], $params['avatar_dir'] );

	/**
	 * Filters the avatar folder directory path.
	 *
	 * @since BuddyPress 1.1.0
	 *
	 * @param string $value Path to the avatar folder directory.
	 * @param int    $value ID of the avatar item being requested.
	 * @param string $value Avatar type being requested.
	 * @param string $value Subdirectory where the requested avatar should be found.
	 */
	$avatar_folder_dir = apply_filters( 'bp_core_avatar_folder_dir', ( $avatar_loc->path . $avatar_loc->dir . $params['item_id'] ), $params['item_id'], $params['object'], $params['avatar_dir'] );

	/**
	 * Look for uploaded avatar first. Use it if it exists.
	 * Set the file names to search for, to select the full size
	 * or thumbnail image.
	 */
	$avatar_size              = ( 'full' == $params['type'] ) ? '-bpfull' : '-bpthumb';
	$legacy_user_avatar_name  = ( 'full' == $params['type'] ) ? '-avatar2' : '-avatar1';
	$legacy_group_avatar_name = ( 'full' == $params['type'] ) ? '-groupavatar-full' : '-groupavatar-thumb';

	// Check for directory.
	if ( file_exists( $avatar_folder_dir ) ) {

		$avatar_url = '';

		// Open directory.
		if ( $av_dir = opendir( $avatar_folder_dir ) ) {

			// Stash files in an array once to check for one that matches.
			$avatar_files = array();
			while ( false !== ( $avatar_file = readdir( $av_dir ) ) ) {
				// Only add files to the array (skip directories).
				if ( 2 < strlen( $avatar_file ) ) {
					$avatar_files[] = $avatar_file;
				}
			}

			// Check for array.
			if ( 0 < count( $avatar_files ) ) {

				// Check for current avatar.
				foreach( $avatar_files as $key => $value ) {
					if ( strpos ( $value, $avatar_size )!== false ) {
						$avatar_url = $avatar_folder_url . '/' . $avatar_files[$key];
					}
				}

				// Legacy avatar check.
				if ( !isset( $avatar_url ) ) {
					foreach( $avatar_files as $key => $value ) {
						if ( strpos ( $value, $legacy_user_avatar_name )!== false ) {
							$avatar_url = $avatar_folder_url . '/' . $avatar_files[$key];
						}
					}

					// Legacy group avatar check.
					if ( !isset( $avatar_url ) ) {
						foreach( $avatar_files as $key => $value ) {
							if ( strpos ( $value, $legacy_group_avatar_name )!== false ) {
								$avatar_url = $avatar_folder_url . '/' . $avatar_files[$key];
							}
						}
					}
				}
			}
		}

		// Close the avatar directory.
		closedir( $av_dir );

		/**
		 * Filters a locally uploaded avatar URL.
		 *
		 * @since BuddyBoss 1.0.0
		 *
		 * @param string $avatar_url URL for a locally uploaded avatar.
		 * @param array  $params     Array of parameters for the request.
		 */
		$avatar_url = apply_filters( 'bp_core_fetch_avatar_url_check', $avatar_url, $params );

		// If we found a locally uploaded avatar.
		if ( isset( $avatar_url ) ) {
			// Support custom scheme.
			$avatar_url = set_url_scheme( $avatar_url, $params['scheme'] );

			// Return it wrapped in an <img> element.
			if ( true === $params['html'] ) {

				/**
				 * Filters an avatar URL wrapped in an <img> element.
				 *
				 * @since BuddyPress 1.1.0
				 *
				 * @param string $value             Full <img> element for an avatar.
				 * @param array  $params            Array of parameters for the request.
				 * @param string $value             ID of the item requested.
				 * @param string $value             Subdirectory where the requested avatar should be found.
				 * @param string $html_css_id       ID attribute for avatar.
				 * @param string $html_width        Width attribute for avatar.
				 * @param string $html_height       Height attribute for avatar.
				 * @param string $avatar_folder_url Avatar URL path.
				 * @param string $avatar_folder_dir Avatar DIR path.
				 */
				return apply_filters( 'bp_core_fetch_avatar', '<img src="' . $avatar_url . '"' . $html_class . $html_css_id  . $html_width . $html_height . $html_alt . $html_title . $extra_attr . ' />', $params, $params['item_id'], $params['avatar_dir'], $html_css_id, $html_width, $html_height, $avatar_folder_url, $avatar_folder_dir );

			// ...or only the URL
			} else {

				/**
				 * Filters a locally uploaded avatar URL.
				 *
				 * @since BuddyPress 1.2.5
				 *
				 * @param string $avatar_url URL for a locally uploaded avatar.
				 * @param array  $params     Array of parameters for the request.
				 */
				return apply_filters( 'bp_core_fetch_avatar_url', $avatar_url, $params );
			}
		}
	}

	// By default, Gravatar is not pinged for groups.
	if ( null === $params['no_grav'] ) {
		$params['no_grav'] = 'group' === $params['object'];
	}

	/**
	 * Filters whether or not to skip Gravatar check.
	 *
	 * @since BuddyPress 1.5.0
	 *
	 * @param bool  $value  Whether or not to skip Gravatar.
	 * @param array $params Array of parameters for the avatar request.
	 */
	if ( ! apply_filters( 'bp_core_fetch_avatar_no_grav', $params['no_grav'], $params ) ) {

		// Set gravatar type.
		if ( empty( $bp->grav_default->{$params['object']} ) ) {
			$default_grav = 'wavatar';
		} elseif ( 'mystery' == $bp->grav_default->{$params['object']} ) {

			/**
			 * Filters the Mystery person avatar src value.
			 *
			 * @since BuddyPress 1.2.0
			 *
			 * @param string $value Avatar value.
			 * @param string $value Width to display avatar at.
			 */
			$default_grav = apply_filters( 'bp_core_mysteryman_src', 'mm', $params['width'] );
		} else {
			$default_grav = $bp->grav_default->{$params['object']};
		}

		// Set gravatar object.
		if ( empty( $params['email'] ) ) {
			if ( 'user' == $params['object'] ) {
				$params['email'] = bp_core_get_user_email( $params['item_id'] );
			} elseif ( 'group' == $params['object'] || 'blog' == $params['object'] ) {
				$params['email'] = $params['item_id'] . '-' . $params['object'] . '@' . bp_get_root_domain();
			}
		}

		/**
		 * Filters the Gravatar email to use.
		 *
		 * @since BuddyPress 1.1.0
		 *
		 * @param string $value Email to use in Gravatar request.
		 * @param string $value ID of the item being requested.
		 * @param string $value Object type being requested.
		 */
		$params['email'] = apply_filters( 'bp_core_gravatar_email', $params['email'], $params['item_id'], $params['object'] );

		/**
		 * Filters the Gravatar URL host.
		 *
		 * @since BuddyPress 1.0.2
		 *
		 * @param string $value Gravatar URL host.
		 */
		$gravatar = apply_filters( 'bp_gravatar_url', '//www.gravatar.com/avatar/' );

		// Append email hash to Gravatar.
		$gravatar .=  md5( strtolower( $params['email'] ) );

		// Main Gravatar URL args.
		$url_args = array(
			's' => $params['width']
		);

		// Custom Gravatar URL args.
		if ( ! empty( $params['force_default'] ) ) {
			$url_args['f'] = 'y';
		}
		if ( ! empty( $params['rating'] ) ) {
			$url_args['r'] = strtolower( $params['rating'] );
		}

		/**
		 * Filters the Gravatar "d" parameter.
		 *
		 * @since BuddyPress 2.6.0
		 *
		 * @param string $default_grav The avatar default.
		 * @param array  $params       The avatar's data.
		 */
		$default_grav = apply_filters( 'bp_core_avatar_default', $default_grav, $params );

		// Only set default image if 'Gravatar Logo' is not requested.
		if ( 'gravatar_default' !== $default_grav ) {
			$url_args['d'] = $default_grav;
		}

		// Set up the Gravatar URL.
		$gravatar = esc_url( add_query_arg(
			rawurlencode_deep( array_filter( $url_args ) ),
			$gravatar
		) );

	// No avatar was found, and we've been told not to use a gravatar.
	} else {

		/**
		 * Filters the avatar default when Gravatar is not used.
		 *
		 * This is a variable filter dependent on the avatar type being requested.
		 *
		 * @since BuddyPress 1.5.0
		 *
		 * @param string $value  Default avatar for non-gravatar requests.
		 * @param array  $params Array of parameters for the avatar request.
		 */
		$gravatar = apply_filters( 'bp_core_default_avatar_' . $params['object'], bp_core_avatar_default( 'local', $params ), $params );
	}

	if ( true === $params['html'] ) {

		/** This filter is documented in bp-core/bp-core-avatars.php */
		return apply_filters( 'bp_core_fetch_avatar', '<img src="' . $gravatar . '"' . $html_css_id . $html_class . $html_width . $html_height . $html_alt . $html_title . $extra_attr . ' />', $params, $params['item_id'], $params['avatar_dir'], $html_css_id, $html_width, $html_height, $avatar_folder_url, $avatar_folder_dir );
	} else {

		/** This filter is documented in bp-core/bp-core-avatars.php */
		return apply_filters( 'bp_core_fetch_avatar_url', $gravatar, $params );
	}
}

Changelog

Changelog
Version Description
BuddyPress 1.1.0 Introduced.