Check If A User Or Author Has Avatar In WordPress And Set User Image With First Letter As Default

Sometimes we do not want WordPress to display the default avatar. There isn’t a WP core function to check that. So we will create one. We will also learn how to add the first letters of the user’s first name and last name as a fallback avatar picture using JavaScript.

Steps to achieve the goal:

There are two things we need to check, If the user has uploaded the gravatar from:
1. WP Dashboard (using wp-user-avatar plugin), or
2. Gravatar site.

If any of the above conditions is true, the user has valid gravatar,
and the function will return true.

1. For Scenario 1: Upload from WP Dashboard:
We check if the query args are present or not.

2. For Scenario 2: Upload on Gravatar site:
When constructing the URL, use the parameter d=404.
This will cause Gravatar to return a 404 error rather than an image if the user hasn’t set a picture.

Create Custom has_avatar function

Let’s create a function and add it in functions.php

/**
 * Checks to see if the specified user id has a uploaded the image via wp_admin.
 *
 * @return bool  Whether or not the user has a gravatar
 */
function is_uploaded_via_wp_admin( $gravatar_url ) {

   $parsed_url   = wp_parse_url( $gravatar_url );

   $query_args = ! empty( $parsed_url['query'] ) ? $parsed_url['query'] : '';

   // If query args is empty means, user has uploaded gravatar.
   return empty( $query_args );

}

Let’s print_r($parsed_url) and see the difference in the URL, when an avatar is uploaded using plugin, and when it’s not.

Avatar uploaded from admin:

Avatar not uploaded:

Notice there is a query key available when an avatar is not uploaded.

Now let’s create another has_gravatar() function which in turn calls the is_uploaded_via_wp_admin() function.

function has_gravatar( $user_email ) {

   $gravatar_url = get_avatar_url( $user_email );
// 1. Check if uploaded from WP Dashboard.
   if ( is_uploaded_via_wp_admin( $gravatar_url ) ) {
      return true;
   }
   // 2. Check if uploaded from gravatar site by adding 404 in the url query param 
   $gravatar_url = sprintf( '%s&d=404', $gravatar_url );

   // Make a request to $gravatar_url and get the header
   $headers = @get_headers( $gravatar_url );

   // If request status is 200, which means user has uploaded the avatar on gravatar ste
   return preg_match( "|200|", $headers[0] );
}

Logic: When constructing the URL, we add the parameter d=404. This causes gravatar to return a 404 error status rather than an image with 200 status if the user hasn’t set a picture.

Notice when the user has uploaded the gravatar on the gravatar site, the status is 200 vs when it’s not it’s 404

Using has_avatar()

Now you can use this function to conditionally render the gravatar. In author.php archive page.

$author_email = get_the_author_meta( 'user_email' );
$has_avatar = has_gravatar( $author_email );
$avatar = get_avatar( $author_email, 251, '', '', ['class' => 'w-251px h-251px object-cover rounded-full'] );
<?php
   if ( !empty( $has_avatar ) ) {
      echo wp_kses_post($avatar);
   } else {
      printf(
            '<span id="author-firstname" class="hidden">%1$s</span><span id="author-lastname" class="hidden">%2$s</span><div id="author-profile-img" class="w-251px h-251px object-cover rounded-full bg-brand-yellow relative"><span class="text-6xl font-lato-bold tracking-0.5px text-white inset-center"></span></div>',
         esc_html( get_the_author_meta( 'first_name', $author_id ) ),
         esc_html( get_the_author_meta( 'last_name', $author_id ) )
      );
   }
?>

You can also add JavaScript to show the initial two letters from JS if the author’s gravatar is not present like so:

( function( $ ) {
   class Author {
      constructor() {
         this.authorProfileImgContainer = $( '#author-profile-img span' );
         this.authorFirstNameText = $( '#author-firstname' ).text();
         this.authorLastNameText = $( '#author-lastname' ).text();
         
         this.init();
      }
      
      init() {
         if ( ! this.authorProfileImgContainer.length ) {
            return null;
         }
         
         let initials = this.authorFirstNameText.charAt( 0 ) + this.authorLastNameText.charAt( 0 );
         initials = initials ? initials : 'A';
         
         // Set the text.
         this.authorProfileImgContainer.text( initials );
      }
      
   }
   
   new Author();
} )( jQuery );

Display the initials of the author Emma Watson i.e ES, when gravatar is not present.

That’s all folks!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *