Skip to content
Advertisement

Check if a User Has a Gravatar [WordPress]

Thanks Rene Korss for helping to resolve the issue almost and be there every time to reply in discussion.

I want to check if the user who has posted comment is having an avatar or not? If user has avatar (means having gravatar account) show gravatar avatar else show image which I have defined in else portion. Any help would be appriciated.

I am currently using this code:

if(get_avatar()==1 )
            {
                echo get_avatar($comment,$size='48',$default='<path_to_url>' ); 
            }
        else
            {   ?>
                <img src="<?php bloginfo('template_directory'); ?>/img/admin.jpg" alt=""><?php 
            }   ?>

Output for this code is only else portion working. And in case I am writing condition as if(get_avatar()) then only if portion working.

$comment has values:

 stdClass Object ( 
 [comment_ID] => 9 
 [comment_post_ID] => 104 
 [comment_author] => Navnish 
 [comment_author_email] => ask@navnishbhardwaj.com
 [comment_author_url] => 
 [comment_author_IP] => 118.146.54.35 
 [comment_date] => 2015-09-23 14:33:11 
 [comment_date_gmt] => 2015-09-23 14:33:11 
 [comment_content] => this is comment by Admin
 [comment_karma] => 0 
 [comment_approved] => 1 
 [comment_agent] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0 
 [comment_type] => 
 [comment_parent] => 0 
 [user_id] => 1 
 )

When used this code:

<?php 
$avatar = get_avatar( get_the_author_meta( 'ID' ), $size = '48', $default = bloginfo( 'template_directory' ).'/img/admin.jpg' ); 
if( $avatar !== false )
{
echo $avatar; 
} 
?>

Got output like this:

enter image description here

Output for:

$avatar = get_avatar( $comment->comment_author_email, $size = '48', $default = bloginfo( 'template_directory' ).'/img/admin.jpg' ); 
if( $avatar !== false )
{
    echo $avatar; 
}

is: enter image description here

Advertisement

Answer

Try with this. Using author email should help. Also, notice that I’m not calling get_avatar twice. else is not needed, because you can set $default image to be used, if avatar dosen’t exist.

$avatar = get_avatar( $comment->comment_author_email, $size = '48', $default = bloginfo( 'template_directory' ).'/img/admin.jpg' ); 
if( $avatar !== false )
{
    echo $avatar; 
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement