• I’ve encountered a problem while trying to incorporate Gravatars into a theme I’m working on. Here’s what I want to do in PHPish English:

    if (gravatar function exists) and (gravatars are enabled) and (gravatar isn't empty) {
      (show gravatar)
    }
    else {
      (show something else)
    }

    I feel rather sure that this should be possible, even easy, but I can find no documentation showing how to do it. I’ve found plenty of ways to check for the function’s existence, but no way to assure that they’re enabled. Similarly, I’ve found the code that’s returned when the gravatar is empty, but no elegant way to check preemptively.

    I think it’s reasonable that this would take two steps (does this blog do gravatars? and does this commenter do gravatars?) or even three, but right now I don’t really know where to begin.

    Any help is appreciated.

Viewing 14 replies - 1 through 14 (of 14 total)
  • try

    if (version_compare($GLOBALS['wp_version'], '2.5', '>='))
    {
      if (get_option('show_avatars')){
       get_avatar($valid_email, $size, $default_avatar_uri);
      }
    }

    first, you’ll need to change the $email, $size & $default_avatar_uri with your own preferences.

    what the code does.
    1. some comprative check for WordPress 2.5 & above, gravatar is full support for that respective version and above only.
    2. check if the ‘show avatar’ options is enabled.
    3. output the gravatar if the email is valid otherwise send the default avatar image (base on $default_avatar_uri) .

    in “PHPish English” it would translate to

    if (wordpress version is equal or larger than 2.5) and (client wanted to show avatar) {
      if (end-user has valid gravatar email) {
      (show gravatar )
      } else {
      (show default avatar)
      }
    } else {
      (raise error "avatar is disabled or maybe not implemented yet")
    }

    lol

    Thread Starter ikiru

    (@ikiru)

    Thanks for the help chaoskaizer. I feel a little embarrassed that I forgot about using get_option for checking that avatars are on.

    That said, I’m still lacking a good solution to the “If avatar is empty show something else” problem. I should have made clear in the original question that I’m not looking to show an image if the commenter has no avatar, but a text string.

    The best thing I’ve thought of for this purpose is to check what’s returned against what I know an empty return should look like. Aside from seeming a little inelegant, I’m not sure my PHP’s up to that.

    Off to tinker, I suppose…

    Moderator Samuel Wood (Otto)

    (@otto42)

    www.ads-software.com Admin

    The get_avatar function itself checks the show_avatars option, so you don’t need to check it in the theme itself. If show_avatars is disabled, the get_avatar function will return false.

    Thread Starter ikiru

    (@ikiru)

    Thanks for in info, Otto. Very good to know.

    But in this case I think I may actually want to check separately so I can say “If function exists and is enabled, do X, else, do Y.” It’s only at X that I want to try to actually get the avatar. (And hopefully do Z if the avatar returned is blank).

    I can’t think of a logical way to make this any shorter in light of the new information. Is there something I’m missing?

    update assume that this are inside $comment loop;

    $default_avatar_uri = 'https://www.gravatar.com/avatar/3b3be63a4c2a439b013787725dfce802';
    $size = 42;
    $valid_email = $comment->comment_author_email;
    if ( (version_compare($GLOBALS['wp_version'], '2.5', '>=') )
     && get_avatar($valid_email, $size, $default_avatar_uri)  ){
    
    } else {
     $hash = md5($valid_email);
     $rating = ( !empty(get_option('avatar_rating')) ) ? get_option('avatar_rating') : 'g';
     $default = ( !empty( get_option('avatar_default') ) ) ? get_option('avatar_default') : $default_avatar_uri ;
    
     $uri = 'https://www.gravatar.com/avatar/'.$hash;
     $uri .= '?d='.urlencode($default).'&s='.$size.'&r='.$rating.'/';
     echo '<img src="'.$uri.'" width="'.$size.'" height="'.$size.'" alt="avatar" class="photo" />';
    }

    Thread Starter ikiru

    (@ikiru)

    That looks interesting chaoskaizer. Am I wrong in thinking that is a backwards compatible version of the gravatar code?

    The problem I’m actually having is that I don’t think there’s any way to tell from the results of get_avatar whether or not it’s returning the default avatar or an avatar that was actually set by a user.

    My code currently looks like this:

    if (function_exists('get_avatar') && ($avatar_results = get_avatar($comment, $size='16'))) {
      if ($avatar_results == 'default_avatar') {
        echo $comment_count;
      }
      else {
        echo $avatar_results;
      }
    } else {
      echo $comment_count;
    }

    What I need is a way to replace the dummy if (avatar_results == 'default avatar') line with a real check to see if it is a default avatar. But I’m increasingly thinking that there’s no good way to do this and I should should stop trying to find it.

    that would require http response header check

    200 && "content-disposition" = true
    200 &&  with no "content-disposition" == 'default: monsterid, identicon, mystery,wavatar'
    302 = false (redirect: revert to default avatar)

    dont do it inside template it will slow down your page. better used Action hook “comment_post” && “edit_post” and store the value somewhere inside %_comments.

    for headers

    function is_valid_gravatar($email,$default='identicon',$redirect = 1)
    {
    	$hash = md5($email);
    	$uri = 'https://www.gravatar.com/avatar/'.$hash;
    	$uri .= '?d='.urlencode($default).'&r=any&size=80';
    
    	$headers = wp_get_http_headers($uri,$redirect);
    
    	if (!is_array($headers)){
    		return false;
    	}
    
    	if ( $headers['response'] == '200'
    	&& isset($headers["content-disposition"]) ){
    			return $uri;
    	} elseif ($headers['response'] == '200'
    		&& !isset($headers["content-disposition"]) ){
    		return false;
    	} elseif ($headers['response'] == '302'){
    		return false;
    	}
    
    }

    if true return “full gravatar url”, if not return bool false.

    Thread Starter ikiru

    (@ikiru)

    It seems I’m swimming beyond my depth…

    I vaguely understand what you’re talking about chaoskaizer, and it seems that you found a very clever way to do what I want, but I have a few questions. I don’t know if you (or anyone else) can answer these, but:

    1. Are these “http response headers” coming with the image that the get_avatar function is pointing me to?
    2. How were you able to tell which codes (200, 302) mean which behavior?
    3. To avoid slowdown, should I put your function in my functions.php file? Or does it go somewhere else?
    4. Can I really avoid slowdown? If the process of checking slows things down, won’t it be slow no matter where/how I check?
    5. Not sure I understand this: “used Action hook “comment_post” && “edit_post” and store the value somewhere inside %_comments.” Are you saying that I should generate the variable separately (like with your function) and only check the value within the actual template file?

    Also, thanks so much for all your help and patience. I didn’t actually know if someone would try to help me, let alone find a solution to my problem. You’re a great asset to the WordPress community, chaoskaizer.

    I’ll bump this thread because I’m looking for the exact same result.

    If the commentor’s given e-mail address has a gravatar, show it. If their e-mail doesn’t have a gravatar, tell them “boo you”.

    I think that’s exactly what ikiru was after as well.

    The reason for me (and probably others) wanting to do this, is so you don’t fill dead space with a default gravatar. If they have one, show it, if they don’t, don’t display any filler images.

    Hey guys. I’ve been working on this problem and have used the code above but made it actually work. What I wanted to do is show a local avatar ONLY if the user doesn’t have an account on Gravatar (free CDN == delicious).

    Using this function may add time to your pageload. What it does is during PHP execution it fetches the proposed gravatar url using wp_get_http_headers() and returns the HTTP headers (you can inspect the http headers for a file in Firefox using the Firebug plugin). It then checks for ‘content-disposition’ in those headers.

    SO: If you have a lot of gravatars you are checking the pageload will have to wait for PHP to check the headers of each file, THEN once it has determined that there is/isn’t a gravatar account and the user recieves the html, the browser will still have to download the gravatar images from the server. If there are a lot then it could take a long long time.

    What Chaoskaiser was saying about using hooks is that if you can avoid checking the gravatars on every pageload then it is very valuable to do so for speed.

    She recommended adding your own plugin function to the post_comment hook, where you could make a note at the moment the comment is saved as to whether the user has a gravatar or not, that way subsequent pageloads wouldn’t be a problem. This is a bit hairy as a recommendation though, because editing the wp_commetns tabel is a bad idea and I can’t think of other good places for it.

    Personally, I’m using this only for my actuall user accounts, so i’m running a cron that checks every user and saves their status (has_gravatar) in the wp_usermeta table so that I don’t have to check the gravatar every time.

    Another option that might be good is to add something to the comments form such that only RIGHT AFTER they post a comment and are brought back to the comment form do you do the check, then, if they dont’ have a gravatar, you put a big link right above their comment saying “you have no image! Go to Gravatar.com and sign up for free!”

    About testing the actual header responses I’m not sure what Chaoskaiser was getting at with the 200/302 response values, but in my testing there was no ‘response’ element at all. Luckily she seems to have hit the nail with ‘content-disposition’ which is only there for gravatars with actual accounts. So my function only uses that one to tell if the person has a gravatar.

    function gv_validate_gravatar($user_id) {
    
    	// Mine is just for user_id, you can work out dealing with emails as well for yourself.
    	$user = get_userdata($user_id);
    
    	// Craft a potential url and test its headers
    	$email = $user->user_email;
    	$hash = md5($email);
    	$uri = 'https://www.gravatar.com/avatar/' . $hash . '?d=identicon&r=any&size=80';
    	$headers = wp_get_http_headers($uri);
    
    	// Check the headers
    	if (!is_array($headers)) :
    		$has_valid_avatar = FALSE;
    	elseif (isset($headers["content-disposition"]) ) :
    		$has_valid_avatar = TRUE;
    	else :
    		$has_valid_avatar = FALSE;
    	endif;
    
    	return $has_valid_gravatar;
    }

    WPChina

    (@wordpresschina)

    Is there a way to show Gravatars of the last 10 people who visited the blog so I can put that on a sidebar? I searched for a plugin but couldn’t find one but maybe there is a hack?

    @wordpresschina:

    This is the code I use in my footer to recall the most recent commentators on my site… Keep in mind that the user_id would need to be changed to whatever your user_id is so as to prevent your gravatar from being displayed with the results… (if you’re the original admin, then it’s probably “1”)

    <?php
    
    $comment_array = $wpdb->get_results(
    "SELECT * FROM $wpdb->comments WHERE user_id <> 1 AND comment_author_email <> '' AND comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 10"
    );
    $comment_total = count($comment_array);
    
    echo '<ul>';
    for ($x = 0; $x < $comment_total; $x++)
    {
    echo '<li>';
    echo '<a href="'.$comment_array[$x]->comment_author_url.'" title="'.$comment_array[$x]->comment_author.'">';
    echo get_avatar($comment_array[$x]->comment_author_email, 50);
    echo '</a>';
    echo '</li>';
    }
    echo '</ul>'
    
    ?>

    I also have comment_author_email <> '' in the code to prevent pingbacks and trackbacks from being displayed.

    YOu can adjust the size of the avatar by adjusting the number in get_avatar($comment_array[$x]->comment_author_email, 50);

    Good luck!

Viewing 14 replies - 1 through 14 (of 14 total)
  • The topic ‘With and Without Gravatars’ is closed to new replies.