Code snippet for using php to randomize a header image based on all files within a folder. The nice thing about this is that if you or the client wanted to add more images or take some out of a image rotation, there would not be the need to update the code everytime.

 

$path = ABSPATH.'art/backgrounds/';
$dir = opendir($path);
$files = array();
while ($file = readdir($dir)) {
if (!is_dir($path.$file) && $file != "." $file != ".." && (strpos($file, '.jpg') == strlen($file)-4 || strpos($file, '.gif') == strlen($file)-4)) {
array_push($files, $file);
}
}
$randInt = rand(0, sizeof($files)-1);

echo "<div id="banner" class="clearfix" style="background: url(/art/backgrounds/".$files[$randInt];."">";

« Back to Blog