Random Header image from a folder

I’ve been designing a new site and the client wanted to have each of her posts freshened up a bit but doesn’t have the time to add images to each post. The images aren’t necessarily required, but add a nice stylistic touch to draw the eye. So I created a folder for the images to sit and created 30 images to choose from (of course we can always add to this).

This script finds the folder in the WordPress theme – the part that was a little tricky was that the glob() function works on a local path rather than a url, so I couldn’t use something like get_stylesheet_directory_uri() directly in the image path. It needed to access the server file-system (get_template_directory) then after getting my random image recreate the url so I could use it in (my case) the background image.

<?php
  $theme_img_path = '/i/jobtitles/';
  $images  = glob( get_template_directory() . $theme_img_path . '*.jpg', GLOB_BRACE );
  $randomImage = $images[array_rand($images)]; 
?>

… and creates a random url that I can then use

<?php echo get_template_directory_uri() . $theme_img_path . basename( $randomImage ); ?>