Random Header Image

Post by 
John Crenshaw
Published 
October 16, 2014

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

  1. 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.
  2. 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 ?>):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function randomHeader() {
 
    # Init files array
    $files = array();
 
    # Set header images directory
    $dir = get_template_directory() . '/images/header_images/';
 
    if(!is_dir($dir))  {
        echo 'The specified header image directory is not a valid directory.';
        // DEBUG
        //echo $dir . '<br />';
    }else{
        if($handle = opendir($dir)) {
            while(($file = readdir($handle)) !== false) {
                if(preg_match('#(.jpg$|.gif$|.png$)#', $file)) {
                    $files[] = $file;
                }
            }
 
            closedir($handle);
 
            # Generate random number between 0 and size of files array
            $num = rand(0, sizeof($files) - 1);
 
            # Echo random header image
            echo '<img src="' .  get_bloginfo('template_url') . '/images/header_images/' . $files&#91;$num&#93; . '" title="' . get_bloginfo('name') . ' Random Header Image" />';
 
        }else{
            echo 'Could not open the specified directory.';
            // DEBUG
            //echo $dir . '<br />';
        }
    }
}
  1. 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:
1
2
3
4
5
6
7
8
9
<?php if(is_home()) { ?>
    <img src="<?php bloginfo('template_url'); ?>/images/header_images/header4.jpg" title="<?php bloginfo('name'); ?> Random Header Image" />
<?php }elseif(is_single()) { ?>
    <img src="<?php bloginfo('template_url'); ?>/images/header_images/header2.jpg" title="<?php bloginfo('name'); ?> Random Header Image" />
<?php }elseif(is_page()) { ?>
    <img src="<?php bloginfo('template_url'); ?>/images/header_images/header3.jpg" title="<?php bloginfo('name'); ?> Random Header Image" />
<?php }else{ ?>
    <img src="<?php bloginfo('template_url'); ?>/images/header_images/header1.jpg" title="<?php bloginfo('name'); ?> Random Header Image" />
<?php } //endif ?>

With this:

1
<?php randomHeader(); ?>

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

1
function randomHeader() {

Create a new function called randomHeader

1
2
3
4
5
# Init files array
$files = array();
 
# Set header images directory
$dir = get_template_directory() . '/images/header_images/';

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().

1
2
3
4
if(!is_dir($dir))  {
    echo 'The specified header image directory is not a valid directory.';
    // DEBUG
    //echo $dir . '<br />';

Here we use is_dir() to test if our directory is, in fact, a real directory, and if not, we display an error message.

1
2
3
4
5
6
7
}else{
    if($handle = opendir($dir)) {
        while(($file = readdir($handle)) !== false) {
            if(preg_match('#(.jpg$|.gif$|.png$)#', $file)) {
                $files[] = $file;
            }
        }

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.

1
2
3
4
5
6
7
closedir($handle);
 
# Generate random number between 0 and size of files array
$num = rand(0, sizeof($files) - 1);
 
# Echo random header image
echo '<img src="' .  get_bloginfo('template_url') . '/images/header_images/' . $files&#91;$num&#93; . '" title="' . get_bloginfo('name') . ' Random Header Image" />';

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].

1
2
3
4
5
6
7
        }else{
            echo 'Could not open the specified directory.';
            // DEBUG
            //echo $dir . '<br />';
        }
    }
}

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.

Never miss
an update

We never share your info. View our Privacy Policy
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
FOLLOW US ON SOCIAL
THere's More

Post you might also like

All Posts
SEO
Jun
3
//
2020

How Long Does SEO Take?

Scroll all the way down for the calculator. We've seen rankings jump to #1 in 3 days. We've also seen it take 2 or more years. So what should you expect?
SEO
Jun
2
//
2020

What's the Difference Between SEO & SEM?

Don't use the terms SEO and SEM. In this article we'll show you better terms to use for more clarity.
Content
Jun
1
//
2020

Your Content is a Product

SEO
May
8
//
2020

How ADT could drive 10x more traffic to their crime maps

SEO
May
7
//
2020

All the SEO Training Courses We Could Find

Subscribe to Our  Channel