PHP Random Image

Posted on: April 18th, 2012

For a current project I had to take an array of images and make one randomly appear at the top of my page. On refresh or a different page, an image would be picked at random and displayed. It had to be something lightweight and I found one that did what I was asking for without any snags.

<?php 

/* 
 * Name your images 1.jpg, 2.jpg etc. 
 * 
 * Add this line to your page where you want the images to  
 * appear: <?php include "randomimage.php"; ?> 
 */  

// Change this to the total number of images in the folder 
$total = "12"; 

// Change to the type of files to use eg. .jpg or .gif 
$file_type = ".jpg"; 

// Change to the location of the folder containing the images 
$image_folder = get_template_directory_uri() . "/images/rotate"; 

// You do not need to edit below this line 

$start = "1"; 
$random = mt_rand($start, $total); 
$image_name = $random . $file_type; 

echo "<img src="$image_folder/$image_name" alt="$image_name" />"; 

?>

A few notes:

To get this to work in a WordPress template you have to concatenate get_template_directory_uri() at the beginning of the file location, unless you want to put the exact URL in (which makes it hard for local testing and then the switch to a server).

This isn’t necessarily the optimal way to do this as you have to name all of your images 1-whatever number you put as your $total, but it is a quick way to get a random image in your WordPress site.

To call this on a page, just use <?php include ‘/path_to_file/rotate.php’; ?>

Source of this PHP (TotallyPHP)

Tags: , ,

previous post: WordPress Editing Editor Role next post: Star Wars Assets