Function and usage of get_avatar() in wordpress

Question

Answers ( 1 )

    0
    2024-01-06T13:16:11+00:00

    The get_avatar() function in WordPress is used to retrieve the avatar image tag (<img>) for a specific user, email address, MD5 hash, comment, or post. Here's a detailed explanation of its usage and parameters:

    Function:

    • Purpose: Retrieves the avatar <img> tag.
    • Usage: Used in WordPress themes or plugins to display a user's avatar.

    Parameters:

    1. $id_or_email (mixed, required): The avatar to retrieve. Can be a user ID, Gravatar MD5 hash, user email, WP_User object, WP_Post object, or WP_Comment object.

    2. $size (int, optional): Height and width of the avatar in pixels. Default is 96 pixels.

    3. $default_value (string, optional): URL for the default image or a default type. Accepts various values such as '404', 'retro', 'robohash', 'monsterid', 'wavatar', 'identicon', 'mystery', 'blank', 'gravatar_default'. The default is the value of the 'avatar_default' option, typically 'mystery'.

    4. $alt (string, optional): Alternative text for the avatar image tag. Default is an empty string.

    5. $args (array, optional): Extra arguments to retrieve the avatar, including:

      • height (int): Display height in pixels. Defaults to $size.
      • width (int): Display width in pixels. Defaults to $size.
      • force_default (bool): Whether to always show the default image. Default is false.
      • rating (string): Avatar rating ('G', 'PG', 'R', 'X'). Default is the 'avatar_rating' option value.
      • scheme (string): URL scheme.
      • class (array|string): Additional classes for the <img> element.
      • force_display (bool): Whether to always show the avatar. Default is false.
      • loading (string): Value for the loading attribute.
      • fetchpriority (string): Value for the fetchpriority attribute.
      • decoding (string): Value for the decoding attribute.
      • extra_attr (string): Additional HTML attributes for the <img> element. Not sanitized.
      • Default for $args is null.

    Return:

    • Type: string|false
    • Value: The <img> tag for the user’s avatar or false on failure.

    Sample Usage:

    // Example: Displaying the avatar for a user with email "user@example.com"
    echo get_avatar( 'user@example.com', 100, 'monsterid', 'User Avatar' );
    

    This example displays an avatar for the specified email with a size of 100 pixels, using 'monsterid' as the default image type and 'User Avatar' as the alt text.

Leave an answer