Rotating Images in a WordPress Theme

Sometimes you want to add a little pizazz to your page and having images rotate each time someone visits your site is an easy way to do that. How can we get this done with the greatest ease?

Let’s say you have a place on your sidebar where you want to have an image appear. Then let’s say you have five different images that you would like to choose from each time the page is loaded. Then let’s say even further that you want the images to appear randomly.

So cutting to the quick, here is the code we can use to get this done:


<?php
$r_num = rand(1,5);
$selected_image = "image_" . $r_num . ".jpg";

/*
the second number above
is the number of images
you want to rotate
*/
?>

<img src="<?php bloginfo('template_url'); ?>
/images/<?php echo $selected_image; ?>"
alt="Random image...hit refresh to change!" />

For this to work properly the theme you are using must have a directory named “images” and that directory must contain your five files.  Those files must be named image_1.jpg, image_2.jpg, image_3.jpg, image_4.jpg and image_5.jpg.

Figuring out where to put the code might be a little confusing,  so you may have to experiment with it.  But if you wanted the image to appear at the top of the sidebar, then paste the code on the first few lines of the sidebar.php file.  If you want the image to appear in the header, then paste the code in the header.php file somewhere after the <body> element.  Play with it a little until you get the images to come up where you want them.

Comments are closed.