How to show avatar only if it exists?

Is there any function in WordPress that allows to hide the gravatar if id doesn’t exists?

I have many authors that doesn’t have a gravatar and all are displayed like this:

Read More
http://prntscr.com/98zsji    

I would like to hide the default image.

I used the function validate_gravatar($email);, but it generated an error:

Fatal error: Call to undefined function validate_gravatar()

If I print $user_email it display correctly the user email.

Related posts

3 comments

  1. You can use validate_gravatar which takes in the email address of the user and returns back true or false.

    validate_gravatar($email); // returns true or false
    

    How to use it in your code:

        $user_email = get_the_author_meta('user_email');        
    
        if(validate_gravatar($user_email)) { 
            $author_avatar = get_avatar( get_the_author_meta( 'user_email', $author_id ), '78', '', get_the_author_meta( 'display_name', $author_id ) );
        }
    
        // Now just echo where ever you want the image, it will show a default image if no gravatar is present.
        if(isset($author_avatar) && !empty($author_avatar)){
            echo '<img src="'.$author_avatar.'" />';
        }
    
       // In your Functions.php
       function validate_gravatar($email) {
        $hash = md5(strtolower(trim($email)));
        $uri = 'http://www.gravatar.com/avatar/' . $hash . '?d=404';
        $headers = @get_headers($uri);
        if (!preg_match("|200|", $headers[0])) {
            $has_valid_avatar = FALSE;
        } else {
            $has_valid_avatar = TRUE;
        }
        return $has_valid_avatar;
       }
    
  2. Here is the filter that will do the trick:

    function ns_filter_avatar($avatar, $id_or_email, $size, $default, $alt, $args) 
    {
        $headers = @get_headers( $args['url'] );
        if( ! preg_match("|200|", $headers[0] ) ) {
            return;
        }
        return $avatar; 
    }
    add_filter('get_avatar','ns_filter_avatar', 10, 6);
    

    To work you have to add value 404 as third argument $default to get_avatar(). Example:

    get_avatar( $user_email, 45, '404' )
    
  3. I have been using the code below for a while and always work for me. The code is checked with PHPCS and WordPress Theme Standards and there is no errors or warnings.

    The script profile-image.js is only enqueued on the respective page user-edit.php, that also applies for the media-upload and Thickbox scripts, this procedure will avoid any possible scripts conflict on your WordPress admin area.

    /**
    *
    * Add custom user profile information
    *
    */
    add_action( 'show_user_profile', 'ns_show_extra_profile_fields' );
    add_action( 'edit_user_profile', 'ns_show_extra_profile_fields' );
    function ns_show_extra_profile_fields( $user ) { ?>
      <h3>Extra profile information</h3>
       <table class="form-table">
        <tr>
            <th><label for="image">Profile Image</label></th>
            <td>
                <img src="<?php echo esc_attr( get_the_author_meta( 'image', $user->ID ) ); ?>" style="height:50px;">
                <input type="text" name="image" id="image" value="<?php echo esc_attr( get_the_author_meta( 'image', $user->ID ) ); ?>" class="regular-text" /><input type='button' class="button-primary" value="Upload Image" id="uploadimage"/><br />
                <span class="description">Please upload your image for your profile.</span>
            </td>
        </tr>
       </table>
      <?php
     }
    
     /**
     * Enqueue a script in the WordPress admin user-edit.php.
     *
     * @param int $pagenow Hook suffix for the current admin page.
     */
     function ns_selectively_enqueue_admin_script( $hook ) {
       global $pagenow;
       if ($pagenow != 'user-edit.php') {
         return;
       }
       wp_enqueue_script('media-upload');
       wp_enqueue_script('thickbox');
       wp_enqueue_style('thickbox');
       wp_register_script( 'profile-image', get_template_directory_uri().'/js/profile-image.js', array('jquery-core'), false, true );
       wp_enqueue_script( 'profile-image' );
      }
      add_action( 'admin_enqueue_scripts', 'ns_selectively_enqueue_admin_script' );
    
      /*
      * Save custom user profile data
      *
      */
      add_action( 'personal_options_update', 'ns_save_extra_profile_fields' );
      add_action( 'edit_user_profile_update', 'ns_save_extra_profile_fields' );
      function ns_save_extra_profile_fields( $user_id ) {
    
        if ( !current_user_can( 'edit_user', $user_id ) )
          return false;
    
        if(isset($_POST['image'])) {
         $imageprofile = sanitize_text_field( wp_unslash( $_POST['image'] ) );
         update_user_meta( $user_id, 'image', $imageprofile );
        }
      }
    

    profile-image.js:

    jQuery(document).ready(function() {
    jQuery(document).find("input[id^='uploadimage']").live('click', function(){
        //var num = this.id.split('-')[1];
        formfield = jQuery('#image').attr('name');
        tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
    
        window.send_to_editor = function(html) {
            imgurl = jQuery('img',html).attr('src');
            jQuery('#image').val(imgurl);
    
            tb_remove();
        }
        return false;
      });
    });
    

Comments are closed.