
Display a random image
By: a guest on
Feb 14th, 2011 | syntax:
PHP | size: 1.11 KB | hits: 179 | expires: Never
<?php
/* Display a random image
Assumes 8 .jpg images in the images/random sub-folder numbered 1 to 8 (1.jpg, 2.jpg etc)
Plus a fallback image called default.jpg.
All images should have the same dimensions.
*/
// define image width in pixels
$random_img_width = 150;
// define image height in pixels
$random_img_height = 150;
// define the first part of the image's url
$random_img_src = get_stylesheet_directory_uri() . '/images/random/';
// Generate a random number from 1 to 8
$random_img_num = rand(1, 8);
// Create a potential image url
$random_img = $random_img_src . $random_img_num . '.jpg';
// Does the image actually exist? If, yes - display it
if( file_exists(get_stylesheet_directory() . '/images/random/' . $img_num . '.jpg')) echo '<img class="random-image" src="' . $random_img . '" width="<?php echo $random_img_width;?>" height="<?php echo $random_img_height;?>" alt="" />';
// If no, use the fallback default.jpg image
else echo '<img class="random-image" src="' . $random_img . '" width="<?php echo $random_img_width;?>" height="<?php echo $random_img_height;?>" alt="" />';
?>