Displaying a gravatar using user email in WordPress posts and pages
Learn how to display gravatar using user email in WordPress posts and pages. This article shows how to use a PHP function to create a shortcode to add a gravatar on WordPress pages and posts.
Gravatars can be used anywhere on a WordPress site which requires you to display a user profile. This article shows you how to display Gravatar for a user using their email address.
Adding a gravatar hovercard on WordPress
Important
Always perform a backup before you make any changes to the theme files. It will be easier for you to revert your site to its last good known state if you break any codes. Alternatively you could also create a child theme. Read this link on how to create a child theme: https://www.hosting.com/blog/wordpress-child-theme/
To add a gravatar hovercard using email, follow the steps below:
-
Log in to your WordPress site with an administrator account.
-
On the Dashboard in the left sidebar, click Appearance, and then click Theme Editor:
Important
You will not be able to roll back to your earlier Theme configuration after any edits. It is recommended to save the Theme file before proceeding with the edits.
-
On the Theme Editor, select the Theme you want to edit from the dropdown:
-
The files for this selected theme is listed on the right column under Theme Files. Click on the file named "functions.php":
-
Insert the following code to the end of functions.php file. The function below is a modified version of the wpbeginner_display_avatar function. The function below creates a shortcode. The shortcode can be used with an email to display the gravatar of the user according to the email address:
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');
- To display the gravatar on the page or post use the following shortcode:
[wpb_gravatar] -- display a gravatar of a current user
[wpb_gravatar wpb_user_email="[email protected]"] -- display a gravatar for the email address.
```
7. The gravatars are displayed as icons on the page or post. In this example, both user profiles do not have an image in the gravatar account. Therefore a default icon is displayed on the page. Hover over the icon to view the gravatar card:

## Related Articles
- [Default gravatar on WordPress](https://kb.hosting.com/docs/default-gravatar-on-wordpress)
- [Displaying the user count in WordPress](https://kb.hosting.com/docs/displaying-the-user-count-in-wordpress)
- [Generating user activity history for WordPress](https://kb.hosting.com/docs/generating-user-activity-history-for-wordpress)
Updated 3 days ago