1

I'm looking for a way to allow the author photo to be shown without the author having a gravatar account.

It seems this should be based on author id rather than email.

Basically I just want to be able to be able to upload author photos to the default media library (date organisation is turned off). These will be named after the author IDs, e.g. author23, author41 etc..

Then on the author's archive pages call <?php echo get_avatar( get_the_author_meta( 'ID' ), 200 ); ?> and instead of Wordpress trying and failing to find an image on gravatar, instead load the relevant image from the site_url/uploads/authorID

What I'm struggling with is how to create the function for this.

1
  • WP doesn't try to find the gravatar, it just creates a URL and it's gravatar that does the finding, WP has no way of knowing if a user has or does not have a gravatar, and there is no local avatar support out of the box. It's something that would have to be added via code. Several plugins exist to do this already
    – Tom J Nowell
    Oct 15, 2022 at 16:51

1 Answer 1

1

One option is to use the pre_get_avatar filter to return custom avatar HTML, which will short-circuit get_avatar() preventing it from reaching out to Gravatar for the image.

For example like this,

add_filter('pre_get_avatar', 'wpse_410434_author_img_html', 10, 3);
function wpse_410434_author_img_html( $avatar, $id_or_email, $args ) {
  if ( $avatar || ! is_numeric( $id_or_email ) ) {
    return $avatar;
  }

  $upload_dir = wp_upload_dir();
  return sprintf(
    '<img class="my-author-avatar" src="%1$s" alt="" width="%2$d" height="%2$d">',
    esc_url(sprintf(
      '%s/author%d.jpg',
      $upload_dir['baseurl'],
      absint( $id_or_email )
    )),
    esc_attr( $args['size'] )
  );
}

N.B Untested, but should work. Tweak to match your exact setup and needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.