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.
![]()
![]()
![]()



Thanks for this code, this script worked wonderfully for my site!
No problem my friend. I’m glad you gave it a try and everything worked out for you.
where do you put this code?
You can put the code anywhere you’d like the image to be displayed. You would, of course, need the webserver to support PHP.
great if the same script worked for the Blogger platform, although some headway has been made recently as far as gravatars/ avatars are concerned – we have still to make stellar strides as far as the WP lesser is concerned – Ah, hope springeth eternal in the bloggosphere :) great tut. keep up the great work , great site !
Mia´s last blog ..Web Treats :" Translucence "