Using WordPress ‘pre_get_avatar_data’ PHP filter

The pre_get_avatar_data filter allows you to modify the avatar URL before it is retrieved. You can use it to change the default avatar or add custom conditions for displaying avatars.

Usage

add_filter( 'pre_get_avatar_data', 'my_custom_pre_get_avatar_data', 10, 2 );

function my_custom_pre_get_avatar_data( $args, $id_or_email ) {
  // your custom code here
  return $args;
}

Parameters

  • $args (array): The arguments passed to get_avatar_data(), after processing.
  • $id_or_email (mixed): The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash, user email, WP_User object, WP_Post object, or WP_Comment object.

More information

See WordPress Developer Resources: pre_get_avatar_data

Examples

Set a default avatar

Set a custom default avatar for users who don’t have a Gravatar.

add_filter( 'pre_get_avatar_data', 'my_custom_default_avatar', 10, 2 );

function my_custom_default_avatar( $args, $id_or_email ) {
  if ( ! isset( $args['url'] ) ) {
    $args['url'] = 'https://example.com/path/to/default/avatar.png';
  }
  return $args;
}

Display different avatars for admins and users

Show a special avatar for administrators and a different one for regular users.

add_filter( 'pre_get_avatar_data', 'my_custom_avatar_for_roles', 10, 2 );

function my_custom_avatar_for_roles( $args, $id_or_email ) {
  $user = false;

  if ( is_numeric( $id_or_email ) ) {
    $user = get_user_by( 'id', (int) $id_or_email );
  } elseif ( is_object( $id_or_email ) ) {
    $user = $id_or_email;
  } elseif ( is_string( $id_or_email ) ) {
    $user = get_user_by( 'email', $id_or_email );
  }

  if ( $user && user_can( $user, 'administrator' ) ) {
    $args['url'] = 'https://example.com/path/to/admin/avatar.png';
  } else {
    $args['url'] = 'https://example.com/path/to/user/avatar.png';
  }
  return $args;
}

Add a custom image size for avatars

Change the avatar image size based on custom conditions.

add_filter( 'pre_get_avatar_data', 'my_custom_avatar_size', 10, 2 );

function my_custom_avatar_size( $args, $id_or_email ) {
  if ( is_singular() ) {
    $args['size'] = 100;
  } else {
    $args['size'] = 50;
  }
  return $args;
}

Use avatars from a custom image hosting

Change the avatar URL to use a custom image hosting service.

add_filter( 'pre_get_avatar_data', 'my_custom_avatar_image_hosting', 10, 2 );
function my_custom_avatar_image_hosting( $args, $id_or_email ) {
    if ( isset( $args['url'] ) ) {
        $args['url'] = str_replace( 'https://secure.gravatar.com', 'https://mycustom.image.hosting', $args['url'] );
    }
    return $args;
}