Side Design Tabs Side Design Tabs
  • Bookmark and Share
  • Tweet This Article?
Leaf.

Display User Avatars On Your Website, Automatically.

  • Published by: Christopher Hennis
  • November 10, 2008

Have you ever wanted to automatically assign and display an avatar or image based on the user who submitted the post or wrote the page? In this tutorial, I’ll show you how, and it couldn’t be easier.

Let’s begin by looking at the PHP code.

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php 
  $urlHome = get_option('home');
  $username = get_the_author_nickname();
   if ($username == "christopher") { 
     $avatar = $urlHome . '/wp-content/themes/treble/img/robotbw.png'; }
   elseif ($username == "alex") { 
     $avatar = $urlHome . '/wp-content/themes/treble/img/robotas.png'; }
   elseif ($username == "admin") {
    $avatar = $urlHome . '/wp-content/themes/treble/img/robotadmin.png'; }
  else { $avatar = 'false'; }
?> 
<?php if ($avatar != 'false') { ?>
<img style="float:left; margin-right:15px; margin-bottom:5px" src="<?php echo $avatar; ?>" alt="avatar" /> <? } ?>
  • Line one sets the variable $urlHome to your website index.
  • Line two sets the variable $username to the user’s nickname specified in the user’s Wordpress options. I prefer to use this as opposed to their login name, because why display the logins to your system when you don’t have to? This defaults to the login name if no nickname is set.
  • The last bit of code in the first part of the PHP above assigns an image to be displayed for the users: christopher, alex, and the admin.
  • The image or avatar is then displayed if the $avatar variable actually contains data and floats the image to the left.

And with a little bit of content and CSS, my specified users would have images, or in this case avatars, automatically displayed.

hellochristopher

helloalex

helloadmin

Subscribe to our RSS Feed

4 Comments

Leave a Reply

Footer Fab Left Footer Fab
© JungleJar.com 2007-2009 All Rights Reserved.