1

Is there a way to show no gravatar in comment list for the commenters that are not registered at gravatar.com? As much as I saw, gravatar.com doesn't return a special code when no avatar is registered.

The temporary, not so elegant solution I applied for the moment is displaying a transparent 1x1px gif but I'd like to return no image if possible.

I've also tried 3-4 gravatar plugins but none does this properly.

0

This plugin hides all avatar images, and preloads them in Javascript, so client side, which should activate the browser cache. If the image exists, the avatar is replaced and made visible. If it does not exist, nothing happens and the avatar image stays hidden. Tested in Safari and Firefox on Mac.

<?php
/*
Plugin Name: WPA 3366
Plugin URI: http://wordpress.stackexchange.com/questions/3366/how-to-display-nothing-instead-default-when-no-user-gravatar-is-present
Description: How to display nothing (instead default) when no user gravatar is present?
Version: 1.0
Author: Jan Fabry
*/

$avatar_collection = array();

function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) {
    if ( ! get_option('show_avatars') )
        return false;

    if ( false === $alt)
        $safe_alt = '';
    else
        $safe_alt = esc_attr( $alt );

    if ( !is_numeric($size) )
        $size = '96';

    $email = '';
    if ( is_numeric($id_or_email) ) {
        $id = (int) $id_or_email;
        $user = get_userdata($id);
        if ( $user )
            $email = $user->user_email;
    } elseif ( is_object($id_or_email) ) {
        // No avatar for pingbacks or trackbacks
        $allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );
        if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) )
            return false;

        if ( !empty($id_or_email->user_id) ) {
            $id = (int) $id_or_email->user_id;
            $user = get_userdata($id);
            if ( $user)
                $email = $user->user_email;
        } elseif ( !empty($id_or_email->comment_author_email) ) {
            $email = $id_or_email->comment_author_email;
        }
    } else {
        $email = $id_or_email;
    }
/*
    if ( empty($default) ) {
        $avatar_default = get_option('avatar_default');
        if ( empty($avatar_default) )
            $default = 'mystery';
        else
            $default = $avatar_default;
    }
*/
    $default = '404';

    if ( !empty($email) )
        $email_hash = md5( strtolower( $email ) );

    if ( is_ssl() ) {
        $host = 'https://secure.gravatar.com';
    } else {
        if ( !empty($email) )
            $host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash{0} ) % 2 ) );
        else
            $host = 'http://0.gravatar.com';
    }

    if ( 'mystery' == $default )
        $default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com')
    elseif ( 'blank' == $default )
        $default = includes_url('images/blank.gif');
    elseif ( !empty($email) && 'gravatar_default' == $default )
        $default = '';
    elseif ( 'gravatar_default' == $default )
        $default = "$host/avatar/s={$size}";
    elseif ( empty($email) )
        $default = "$host/avatar/?d=$default&s={$size}";
    elseif ( strpos($default, 'http://') === 0 )
        $default = add_query_arg( 's', $size, $default );

    if ( !empty($email) ) {
        $out = "$host/avatar/";
        $out .= $email_hash;
        $out .= '?s='.$size;
        $out .= '&d=' . urlencode( $default );

        $rating = get_option('avatar_rating');
        if ( !empty( $rating ) )
            $out .= "&r={$rating}";

        $comment_id = get_comment_ID();

        $avatar = "<img alt='{$safe_alt}' src='about:blank' class='avatar avatar-{$size} photo avatar-{$email_hash} avatar-hidden' height='{$size}' width='{$size}' style='display: none' id='avatar-{$comment_id}'/>";
        $GLOBALS['avatar_collection'][$out][] = $comment_id;
    } else {
        // Empty email: never show an avatar
        $avatar = '';
//      $avatar = "<img alt='{$safe_alt}' src='{$default}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />";
    }

    return apply_filters('get_avatar', $avatar, $id_or_email, $size, $default, $alt);
}

add_filter('wp_print_footer_scripts', 'add_avatar_footer_script');
function add_avatar_footer_script()
{
    global $avatar_collection;
    if (empty($avatar_collection)) {
        return;
    }
    $avatar_data = json_encode($avatar_collection);
    echo <<<EOF
<script type="text/javascript">
(function (avatars) {
    for (var url in avatars) {
        var avatarImageObj = new Image();
        avatarImageObj.onload = function(e) {
            var avatarIds = avatars[e.target.src];
            for (var i = 0; i < avatarIds.length; i++) {
                var avatarImageEl = document.getElementById('avatar-' + avatarIds[i]);
                avatarImageEl.src = e.target.src;
                avatarImageEl.style.display = "block";
            }
        }
        avatarImageObj.src = url;
    }
})({$avatar_data});
</script>
EOF;
}
| improve this answer | |
  • lovely, thanks, tested on Chrome/Leopard, FF/XP, not working in IE7/XP - bu then gravatars are less than totally necessary :) – pax Nov 4 '10 at 23:08
2

There is a easy way with wordpress built-in function to get avatar.

get_avatar( $id_or_email, $size, $default_value_when_no_avatar_found );

if you set this variable to:

$default_value_when_no_avatar_found = 'https://yourdomain.com/image_default.jpg';

This will set your default image if gravatar is not found. You can make this image tiny or whatever you wish to do.

More info: https://codex.wordpress.org/Function_Reference/get_avatar

Also, Gravatar are now built-in into wordpress which means you won't need any plugin to pull it.

More info: https://codex.wordpress.org/Using_Gravatars

Update:

I had similar problem and I used this above solution somewhere but I used different solution for another website that i have, which is:

$avatar_url = get_avatar_url( $ID, array( 'size'=>200, 'default'=>'404' ) );

if( getimagesize( $avatar_url ) > 1 )
{
    echo '<img src="'. $avatar_url .'" alt="" class="avatar avatar-200">';
}

This will show only images that exists in gravatar.

| improve this answer | |
1

If memory serves, gravatar does a 302 to the default if no gravatar is available.

Thus, you could try using CSS. Something like:

img[src=default_gravatar_url] { display: none; }

Or:

img[src=default_gravatar_url] { visibility: hidden; }

(It won't work in all browsers.)

Or you could use jQuery. Something like:

$('img[src=default_gravatar_url]').ready(function() {
  $(this).remove();
});

Both options should be benign in terms of performance.

| improve this answer | |
  • If you want this to work, you need to set the d parameter to another URL. This will indeed cause the redirect. But I don't know how good browsers are at reading the actual location, and not just the value of the src attribute. – Jan Fabry Oct 28 '10 at 14:19
  • the CSS way wouldn't work, while there is a default image served, there's no default image src as it's always based on comment poster's email. It looks like: <img src="http://www.gravatar.com/avatar/d74223421ddabece6c8f85989d0784b2?s=40&d=http://uri-for-default-image" /> – pax Nov 1 '10 at 1:00
  • Aye. As I wrote, try... :-) I'm a bit out of ideas on that one if the above is incorrect. (Though I do know that an http request per comment is very, very bad for performance.) – Denis de Bernardy Nov 1 '10 at 11:05
0

I have modified a tiny bit of the official php example at gravatar.com if $d='404' the function returns a 404 instead of an image so I do a final check, if it returns an image then getimagesize() before the end returns something and the function goes on printing the image

function get_gravatar( $email, $s = 80, $d = '404', $r = 'g', $img = true, $atts = array() ) { //changed $d='404'
$url = 'http://www.gravatar.com/avatar/';
$url .= md5( strtolower( trim( $email ) ) );
$url .= "?s=$s&d=$d&r=$r";
$curl=$url;
    if ( $img ) {
    $url = '<img class="paxvatar" src="' . $url . '"';
    foreach ( $atts as $key => $val )
        $url .= ' ' . $key . '="' . $val . '"';
    $url .= ' />';
}
if (getimagesize($curl)) echo $url; //changed - added getimagesize(check)
}

It probably isn't the most elegant solution, but it's the only way I could get around it.

| improve this answer | |
  • I would at least add some caching to this. Now you do a HTTP request for each comment you display? Maybe you could also do this in Javascript: let a script pre-load all images and only display those that exist. That way the browser cache can do it's work. – Jan Fabry Oct 28 '10 at 7:24
0

If you want to use local caching on server, you can complete it with image processing scripts like Timthumb

| improve this answer | |
0

I combined some of the other solutions for my own.

In order to use Denis de Bernardy's answer we need to provide gravater with a default value, so we can target it in the CSS.

We can do this if we provide our own comment formatting callback function to wp_list_comments wherever we call it in our template.

In our callback we can use Anil's answer to pass a default value to get_avatar.

In your template files where you call wp_list_comments, add a callback function like so:

wp_list_comments(['callback' => 'my_format_comment']);

In your functions.php file declare a new comment formatting function, copying the Wordpress code (full code below) and changing this line:

<?php if ( 0 != $args['avatar_size'] ) echo get_avatar( $comment, $args['avatar_size']' ); ?>

To this:

<?php if ( 0 != $args['avatar_size'] ) echo get_avatar( $comment, $args['avatar_size'], 'identicon' ); ?>

Then you can add CSS like this:

.comment-author img[src*="identicon"] {
    display: none;
}

The full comment formatting function looks like this (I have also replaced a call to $this):

function my_format_comment($comment, $args, $depth) {

    $tag = ( 'div' === $args['style'] ) ? 'div' : 'li';
    ?>
    <<?php echo $tag; ?> id="comment-<?php comment_ID(); ?>" <?php comment_class( count($comment->get_children()) ? 'parent' : '', $comment ); ?>>
    <article id="div-comment-<?php comment_ID(); ?>" class="comment-body">
        <footer class="comment-meta">
            <div class="comment-author vcard">
                <?php if ( 0 != $args['avatar_size'] ) echo get_avatar( $comment, $args['avatar_size'], 'identicon' ); ?>
                <?php
                /* translators: %s: comment author link */
                printf( __( '%s <span class="says">says:</span>' ),
                    sprintf( '<b class="fn">%s</b>', get_comment_author_link( $comment ) )
                );
                ?>
            </div><!-- .comment-author -->

            <div class="comment-metadata">
                <a href="<?php echo esc_url( get_comment_link( $comment, $args ) ); ?>">
                    <time datetime="<?php comment_time( 'c' ); ?>">
                        <?php
                        /* translators: 1: comment date, 2: comment time */
                        printf( __( '%1$s at %2$s' ), get_comment_date( '', $comment ), get_comment_time() );
                        ?>
                    </time>
                </a>
                <?php edit_comment_link( __( 'Edit' ), '<span class="edit-link">', '</span>' ); ?>
            </div><!-- .comment-metadata -->

            <?php if ( '0' == $comment->comment_approved ) : ?>
                <p class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ); ?></p>
            <?php endif; ?>
        </footer><!-- .comment-meta -->

        <div class="comment-content">
            <?php comment_text(); ?>
        </div><!-- .comment-content -->

        <?php
        comment_reply_link( array_merge( $args, array(
            'add_below' => 'div-comment',
            'depth'     => $depth,
            'max_depth' => $args['max_depth'],
            'before'    => '<div class="reply">',
            'after'     => '</div>'
        ) ) );
        ?>
    </article><!-- .comment-body -->
    <?php
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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