
Note: Our example was done for a membership site. So we are grabbing the email address by pulling logged in user’s information. However, the technique of displaying gravatar from email address stays the same.
Displaying Gravatar from User Email in WordPress Template Files
First, we will show you how to display gravatar in your WordPress
templates by using a simple function. Add this code in your theme’s
functions.php
file or in a site-specific plugin. function wpbeginner_display_gravatar() { global $current_user; get_currentuserinfo(); // Get User Email Address $getuseremail = $current_user->user_email; // Convert email into md5 hash and set image size to 32 px $usergravatar = 'http://www.gravatar.com/avatar/' . md5($getuseremail) . '?s=32'; echo '<img src="' . $usergravatar . '" class="wpb_gravatar" />'; }
To display gravatar in your WordPress templates use this code.
<?php wpbeginner_display_gravatar(); ?>
Displaying Gravatar from User Email in WordPress Posts, Pages and Widgets
Now lets assume that you do have email address of a user and
permission to use their gravatar on your site. But you don’t have them
as a registered user on your site. Or that you want to display the
gravatars of selected users in a post, page or a widget. To solve this
problem add this code in your theme’s functions.php file or in a site-specific plugin:
function wpb_display_gravatar($atts) { extract( shortcode_atts( array( 'wpb_user_email' => '', ), $atts ) ); if ($wpb_user_email == '') { global $current_user; get_currentuserinfo(); $getuseremail = $current_user->user_email; } else { $getuseremail = $wpb_user_email; } $usergravatar = 'http://www.gravatar.com/avatar/' . md5($getuseremail) . '?s=32'; echo '<img src="' . $usergravatar . '" />'; } add_shortcode('wpb_gravatar', 'wpb_display_gravatar');
What we have done in the above code is that we modified the original
wpbeginner_display_avatar function and created a shortcode. This
shortcode wpb_gravatar accepts one paramater wpb_user_email. If you have
specified an email address parameter in your shortcode, then it
displays gravatar for the email address provided in the shortcode
instead of the current user. This shortcode can be used in posts, pages,
and widgets. To display the gravatar of the current user use this
shortcode:
[wpb_gravatar]
To display the gravatar of a user email address use shortcode like this:
[wpb_gravatar wpb_user_email="john.smith@example.com"]
You can also add CSS by adding
.wpb_gravatar
class to your stylesheet. Like this: .wpb_gravatar { padding: 3px; margin: 3px; background:#FFFFFF; border:2px solid #eee; }
We hope that you found this article useful in displaying gravatar
from user email address in WordPress. If you have questions or feedback
please leave a comment.
Comments
Post a Comment