Displaying Random Images in Wordpress

Thursday, October 29th, 2009

Small code snippet that will allow you to display random images, every time the page loads. Major advantage of using it is that you no longer have to make use of scripts (JavaScript) which can be bulky, especially on the older browsers. Though we have used this code with images only, it can be easily used for any other object to be displayed in random order. It’s more of PHP than Wordpress.

Code

Place this code anywhere in your Wordpress template – header, footer, etc, with appropriate changes to CSS.

<div id="image<?php echo rand(1,4); ?>"></div>
 

Change (1,4) depending upon the number of images.

CSS

Add this CSS code to the Wordpress template CSS file.

#image1 {
background:url(img/image1.jpg);
width:500px;
height:100px;
}
#image2 {
background:url(img/image2.jpg);
width:500px;
height:100px;
}
#image3 {
background:url(img/image3.jpg);
width:500px;
height:100px;
}
#image4 {
background:url(img/image4.jpg);
width:500px;
height:100px;
}
 

 

Discussions