Adding Gravatars to the User Meta

By Alex on December 30 2008 | Listed under Tutorials, WordPress | No Comments

Quite a lot of blogs make use of the Meta Widget or a function to display login/out capability in their sidebar. Once logged in, all sorts of information can be retrieved about the user, which will allow us to display their Gravatar, giving the feeling that you are really part of that blog.

This is some very simple code that you can use in conjunction with wp_meta, or wp_loginout, or even just on its own, and is highly extendible to fit your needs.

First of all we need to check whether a user is logged in or not, and WordPress already has a function for this, is_user_logged_in.

1
<?php if (is_user_logged_in()){

Then some globals are retrieved following this page of the codex on get_currentuserinfo, and then that function is called.

2
3
global $user_email, $user_login;
get_currentuserinfo();

We then pass these to the normal Gravatar function.

4
echo "<li>" . get_avatar( $user_email, 60) . "</li>";

And finally, just to show another option, the username of the logged in user is output.

5
echo "<li>Logged in as <strong>" . $user_login . "</strong>.</li>";

Then the if statement needs to be closed, and an else statement states that if the user is not logged in then nothing is displayed.

6
7
} else {
} ?>

So all of that code together:

1
2
3
4
5
6
7
<?php if (is_user_logged_in()){
global $user_email, $user_login;
get_currentuserinfo();
echo "<li>" . get_avatar( $user_email, 60) . "</li>";
echo "<li>Logged in as <strong>" . $user_login . "</strong>.</li>";
} else {
} ?>

Demo

If you want to see this in action using your Gravatar, you can register at my test blog and login to see your gravatar and username in the right-hand sidebar.

Extending the Idea

Why not add this code to your comments form, or if you use a preview plugin to show what the comment will look like, logged in users will see their Gravatar there.

This code could also be added to the WordPress admin panels, again making the user feel more a part of the community of your blog.

Have fun with it!

31 Days to Build a Better Blog Affiliate Link

Did you enjoy this post? If you did, so might others! Please share it!

Post a Comment

Your email is never published nor shared.

*
*
User Gravatar