Call Us Today! (866) 377-4331 or Request a Quote

Random Header Image

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 ?>):
    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[$num] . '" title="' . get_bloginfo('name') . ' Random Header Image" />';
    
            }else{
                echo 'Could not open the specified directory.';
                // DEBUG
                //echo $dir . '<br />';
            }
        }
    }
  3. 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:
    <?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:

    <?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

function randomHeader() {

Create a new function called randomHeader

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

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.

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

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[$num] . '" 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].

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

34 Comments
  1. Great !

    I won’t use it right now but I am sure I will do it later ….
    I have been using your theme for one month and I really enjoy it. You’ve done a great job !
    Thanks
    Seb

  2. I get an error message:
    “Parse error: syntax error, unexpected T_STRING, expecting ‘,’ or ‘;’ in /home/stolbud/public_html/coin/wp-content/themes/this-just-in/functions.php on line 33″

    Line 33 in my case says:
    “echo ‘The specified header image directory is not a valid directory.’;”

    Can you help?

  3. And one more question – can I have my random header images in the directory named header_XXX where XXX is a name I will come up with, or do I have to keep them numbered like header1, header2… header99 ?

  4. @Darek: Check that your single quotes are actually single quotes and not the slanted single quotes…also, I’m assuming you added the double quotes to what you quoted as your line 33, correct?

    The images can be named anything you want, as long as they’re in a directory named header_images within the images directory.

  5. John,

    My line 33 looks exactly like that:
    echo ‘The specified header image directory is not a valid directory.’;

    I can send you my functions.php file to view if you like. Thanks for looking into that.

  6. @Darek: Ok, did you check single quotes?

  7. John,

    Single quote made it for line 33.
    Now I have the following error:
    “Parse error: syntax error, unexpected T_VARIABLE in /home/stolbud/public_html/coin/wp-content/themes/this-just-in/functions.php on line 40″

    Line 40 in my case is:
    $files[] = $file;

    any clue?

  8. Hi John,

    The tutorial is very nice!! I learned how to create navigation tabs for new page.I have a question which relates to Random Header Image.

    I have several pages such as about, news, and …. I hope that each page can has its own header image. For example, in my blog section it has its own header image. I guess header3.jpg is for pages but I don’t know how to modify the php file. Could you please teach me how to do? Thank you for your time!

  9. @Darek: Any errors like that are most likely due to the wrong characters being copied or you’re missing a character somewhere. Make sure the code matches exactly, except that slanted single quotes in the code above should be straight single quotes. You’ll probably also have to replace double quotes. (I’m working on making the code copy and pasteable).

  10. @ya-chi Peng: Check the wordpress forums…there’s a lot of general wordpress support on that site.

  11. thanks!

  12. John,

    I’ll wait for the copy & pasteable code as I checked the characters 2 times and it looked all right to me.
    Thanks for help :)

  13. I am not able to get 8 images to work with the “This Just In” theme. Could someone please post the entire function.php code needed without the line numbers to get this random header image code to work. I must not be inserting the new code at the correct place or messing up the syntax. Thanks

  14. Also, I can only get the header image to show up on the home page. How can I get the photos to randomly show up on all pages and posts?

    Thanks

  15. OK. I figured out why my header images were not showing up on all pages. My screw-up. Still need help with function.php file. Thanks again.

  16. Hey, I’m having lots of difficulty implementing this into my site. I copied and pasted the code provided into the files you mentioned “function and header.php” When i preview the site i get nothing but a blank screen. No error messages nothing. I call a test function from the header file and it echos but the function you wrote does not respond at all. Can you help. I’m running wordpress Version 2.6.2

  17. Got my images to rotate by using the script listed in the forum by Darek Czepiel. <img src=”/images/header_images/header.jpg” Thanks

  18. @Sebastian: If you copied and pasted the code make sure you replace single quotes as described in previous comments. You may find other errors with copying and pasting…I’ll work on solving that problem sometime in the near future.

  19. Got it working!

    Copy and Pasteable text:

    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 . ”;
    }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 ”;
    }else{
    echo ‘Could not open the specified directory.’;
    // DEBUG
    //echo $dir . ”;
    }
    }
    }

  20. I’m going through it now and typing up the function by hand in notepad to make sure there are no hidden characters and other naughtiness coming through in cut-and-paste. How about just posting a new functions.php to upload into the template folder?

  21. Follow-up replacing all single and double-quotes did the job for me. I’m stoked! Thanks for the tute!

  22. John,
    Thanks for this theme. I am trying to use a chimage script to protect my random header images. Is it possible to write a line of code in header.php that would show images on all types of pages without having to use the elseif shown below:

    1.

    2.
    <img src=”/images/header_images/header4.jpg” title=” Random Header Image” />
    3.

    4.
    <img src=”/images/header_images/header2.jpg” title=” Random Header Image” />
    5.

    6.
    <img src=”/images/header_images/header3.jpg” title=” Random Header Image” />
    7.

    8.
    <img src=”/images/header_images/header1.jpg” title=” Random Header Image” />
    9.

    I can get my chimage to work on the home page but not on the other single, page or else pages.

    This is what I am using:

    <image src=”chimage.php?image=header.jpg” title=”Random Header Image” />

    <image src=”chimage.php?image=header.jpg” title=”Random Header Image” />

    <image src=”chimage.php?image=header.jpg” title=”Random Header Image” />

    <image src=”chimage.php?image=header.jpg” title=”Random Header Image” />

    Any help would be appreciated.

    Thanks

  23. To everyone having trouble with copying and pasting the code…I’ve finally gotten around to changing the syntax highlighter so that you can copy and paste without getting a bunch of jacked up characters. Click the “view plain” link on any code box and it’ll give you plain text to copy. Let me know if there are any errors.

    @ppaw: I’m not familiar with chimage – what is it supposed to do for you?

  24. OK, this might sound like a really dumb question, but I"m new at this and I was lost at the "create a new functions file in the theme directory"…can someone help me out with this?
    jmcdou02@uoguelph.ca

  25. Hi, I tweaked your code about to make it work for the things I wanted to do… Maybe you are interested in this:

    http://www.loozabeats.de/2008/11/better-random-he…

    I really just wanted to check if it's okay with you, please drop me a line if you feel that I should not post about this on my page.

  26. I got the random header to work in Firefox, but not Explorer. I tried Looza’s changes, but still no luck in Explorer. With your code I’m getting a blank header with a boxed “X” icon, and with Looza’s I’m just getting a blank header. But as I said, in Firefox, both worked like a charm.

    Any suggestions for what I can change to get Explorer to work?

    Thanks!
    jpotter

  27. John

    Great tutorial, I will try to get it to work tonight. I have two embarrassing questions for you. In your “preview” of “this just it” there was a widget on the side that had a small blurb labeled “about”. I cannot find this to add as a widget. What am I doing wrong? Also, I have put the RSS feed into my side bar as a widget setting but it does not seem to show up on my blog site, again what the heck am I doing wrong?

    Thanks

  28. Love it! Thank you John for the great theme and all the help in how to tweak it to make it more personal! :)

  29. Hi John,
    Is thee any way to make the images hyperlinked so that the images are still random but each image has its own hyperlink?
    Thanks,
    Ed