If you've used my theme, This Just In!, you know that there are 4 different header images, which one is displayed depends on which page is currently being viewed. That's a fine setup for some, but quite a few people have requested a method to display the header images at random instead.
In this tutorial, we'll add a new function to our functions.php file in our theme directory (create one if it doesn't already exist). Then we'll add a new function that scans a dedicated header images directory for any header images and loads their locations into memory. This function will be able to handle JPEGs, PNGs, and/or GIFs in any combination.
At that point the function will generate a random number using the PHP rand() function and select an image to display based on that number. After we've built this function, we'll make sure all of our header images are in a folder of their own and then we'll replace the header image code with a call to our newly coded random header image function.
Creating the New Function
- First things first, we'll need a functions.php file in our theme directory, so if you don't already have one, create that now.
- Next, we need to add the following code to that file (if you're creating a new functions.php file, make sure the file starts with <?php and ends with ?>):
- Once you've added that code to functions.php, replace the code that currently displays your header images (in header.php for This Just In!) with a call to that function. For instance, if you're using This Just In!, you'll replace this:
With this:
Create a Dedicated Header Images Directory
The code above assumes you have a dedicated folder where you store all your header images, and that folder must be called "header_images", and it must be inside of your "images" folder within your theme directory. If it's not set up this way, the above code will require some tweaking.
Once you've created the "header_images" directory within your theme's "images" directory, place all the images you want randomly displayed in that new directory.
Now you're ready to rock and roll. For those of you interested, the rest of this post is an explanation of the code.
Code Explanation
The code is fairly simple. Basically, we start by initializing a few variables, then we check to see that the directory where we expect to find our images is, in fact a directory. If it's not we display an error message and the function ends.
If it is a directory, we attempt to open the directory using opendir(). If the directory cannot be opened, we display an error message and the function ends. If the directory can be opened, we read each item in the directory using readdir(). As we cycle through each item in the directory, we use a regular expression to check that the filename ends in .jpg, .gif, or .png, and, if it does, we add that filename to an array of files.
Once we've looped through the directory, we close the connection using closedir() and then move onto choosing which image to display.
To randomly display an image, we generate a random number using the rand() function, with a minimum value of 0 (since arrays – ours included – start at index 0), and a maximum number equal to the size of the files array minus 1. The reason we get the size of the files array using sizeof() and then subtract 1 is because sizeof() returns the actual number of items in the array. So if we have an array with 3 items, sizeof() will return 3, but the actual indexes of those items would be 0, 1, and 2, so we want a random number between 0 and 2 (or 3-1).
Step by Step
Create a new function called randomHeader
Initialize the variable $files as an array and set the directory to open when searching for our header images. We use the built-in WordPress function, get_template_directory() to return an absolute path on the server to the current template directory, which is just what we need in order to open that directory using opendir().
Here we use is_dir() to test if our directory is, in fact, a real directory, and if not, we display an error message.
If it is a directory, we attempt to open the directory using opendir(), and we continue only if we are able to open the directory.
Then we use readdir() to iterate through each file within the directory. The loop executes as long as the readdir function does not return false. Incidentally, we use the !== operator here because the readdir() function can return 0, which, if we were using != would be considered the same as false, which we don't want.
Next we use a regular expression to test if the file ends in ".jpg", ".gif", or ".png" (without the quotes – obviously). If it does end in one of those three extensions, we add that file to the $files array.
Next we close the directory link and generate oru random number. The rand() function accepts 2 parameters, the first being the minimum number to generate and the second being the maximum number to generate. Since the first item in our $files array is $files[0], we need the minimum number to be 0. The sizeof() function returns the number of items in our $files array, but the number of items is actually 1 number higher than the index of the last item (because the first item is $files[0] and not $files[1])…so we subtract 1 from the count returned by sizeof().
Then we echo our img tag. The important part is the $files[$num].
That else executes if we were unable to open the directory to read the images.
Conclusion
As you can see, this is a fairly simple method of displaying random header images on your blog. The power of this method lies in the fact that you can have any number of images and they can be any combination of GIFs, JPEGs, or PNGs, and the script will handle everything for you. If you add or remove images in the future, the script will still function just fine.
One thing you should be aware of is that if you're using one of the popular caching plugins, these images will be cached and as a result, won't be displayed randomly. In order to solve that, you'll need to disable caching of your header images in whichever caching plugin you're using.