Make a Gravatar shortcode

If you are a developer or worked with WordPress before, then you should know what a gravatar is. For those that dont know what a gravatar is, can visit this page.

Your Gravatar is an image that follows you from site to site appearing beside your name when you do things like comment or post on a blog. Avatars help identify your posts on blogs and web forums, so why not on any site? – Gravatar .com

iadminwp gravatar

If you are planning to build a WordPress Plugin or Theme then this little shortcode may help you. I am going to show you how to call the gravatar by using the current user email. Also see this documentation on WordPress.org.

Let us start:

  1. Open your functions.php (please use a child theme)
  2. Create a function, I call it “get_my_gravatar“.
  3. Get User ID, we use the “get_current_user_id()
  4. Now we can get the user metadata “get_userdata($user_id)
  5. We can now get the current user email “$user_info->user_email
  6. Bind the email to the avatar and make the size “64”. The size will depend on how big you want to make it.
  7. Last “return” the value. You can use “echo” also.
  8. Give the shortcode a name, I called it “getmygravatar”. So you can call [getmygravatar] in your post or page.
function get_my_gravatar(){
  $user_id = get_current_user_id();  //get current user ID
  $user_info = get_userdata($user_id); // get current user meta fields
  $myemail = $user_info->user_email; // get current user email
  $getitnow =  get_avatar( $myemail, 64 ); // Bind the email to the gravatar
  return $getitnow; //show it
}
add_shortcode('getmygravatar', 'get_my_gravatar'); // create shortcode [getmygravatar]

This will only work if the user is logged in, so you would need to setup so “if” functions and build in some functions to make it bulletproof.

That is it, now you know the very basic function to call the user avatar. If you have any questions, please email us or leave a comment.

iadminwp gravatar
Once a week we send a digest with the most popular articles.

We are more than just a Hosting company!

AdminWP Host, Maintain (Site-care), Secure and Backup WordPress websites.