Subscribe to
Posts
Comments
NSLog(); Header Image

WordPress Random Header Images

I've received a few comments on my random header images script. One person wrote today asking me to share my "howto," as his method doesn't work with WP-Cache. This should be fairly easy, so, here goes.

The trick to getting random content in WP-Cache is simple: the use of an "mclude" comment. Since my sites are always fairly modular, I employ PHP's include() function frequently, and so it should come as no surprise that my header rotator is included in the page. This makes marking some random content in a cached file rather easy. In my "header.php" file, I have:

<!--mclude /path/to/my/theme/header_rotator.inc-->
<? include('header_rotator.inc'); ?>
<!--/mclude-->

By the way, please note that while I use <?, some PHP purists prefer <?php as the former requires "short opening tags" to be enabled.

The contents of my header_rotator.inc file look a bit like this:

<?
function get_random_header_image()
{

I like to bundle even simple code into functions because it makes calling the function later easier. If I did everything in PHP, I'd likely end up with a nasty echo statement full of "\" characters to escape either ' or ".

    switch(date('md'))
    {
        case '0101':
            return '_newyear'; break;
        case '0323':
            return '_birthday'; break;
        case '1031':
            return '_halloween'; break;
        case '1225':
            return '_christmas'; break;
        default:
            break;
    };

The first part of the function quickly checks the date to see if it's one of a few holidays for which I've set aside some special images. This completely does away with the idea of random images a few times per year, but… so be it.

    $header_imgs[] = 'first_image';
    $header_imgs[] = 'second_image';
    $header_imgs[] = 'third_image';

Here I build an array of possible images. I could scan a directory on my server and list every image available, but I prefer to have a little more control over the order and inclusion of images. For example, I don't want my "holiday" images (above) included, but they're located in the same directory. So, I make use of some PHP shorthand and build a list of images. I could build the array a lot faster than I do above, but I like to keep each image on its own line, because it makes it easier to count them:

    if($_GET['toppic'])
    {
        $num = $_GET['toppic'];
        return $header_imgs[($num-1)];
    }

And that's why I like to count them. If I specify ?toppic=19 (or &toppic=19) on any of my images, I'm guaranteed to get the same one repeatedly. This is useful when I want to show off a new header image, check to see whether it even looks good within the context of my site, etc. Most of the time, of course, this value is ignored.

    else
        return $header_imgs[rand(0, count($header_imgs)-1)];
}    
?>

Failing to meet a "holiday" condition or to have an image specified via toppic, the function returns a random value from anywhere in the array. Remember to subtract one, since arrays start counting at 0.

Finally, outside of PHP's processing, write the HTML necessary to get your image on-screen:

<div id="headerimage">
<img src="/path/to/my/theme/img/headers/<?=get_random_header_image();?>.jpg"
height="189" width="760" alt="NSLog(); Header Image" />
</div>

Since my header image's path, height, width, and alt tags are all the same, I include that data in one place: the actual HTML. This lets every portion of the PHP function return only the image's base name without worrying about the extension (another bit of redundant data). If you have a mix of PNGs and JPEGs, well, you'll need to modify the source to account for that.

At any rate, the call is mostly HTML, with one simple call into the function to get the image's basename and to plug it into an <img> tag. Note that I'm again using some shorthand: <?= is shorthand for <?php echo.

And that's it.

Sidebar Image
My sidebar images not only include different variables like varying height, but they also include text beneath each one. I'll just post an example of this code without much explanation.

Naturally it starts with this in sidebar.php:

<!--mclude /path/to/my/theme/side_pictures.inc-->
<? include('side_pictures.inc'); ?>
<!--/mclude-->

Next I set up a short array of arrays. The $pics array contains arrays of image parts. The image parts are: basename, title, and caption.

<?  $pics[] = array('image_1', 'Alt Number One', 'First Caption');
    $pics[] = array('image_2', 'Second Alt', 'Caption Two');
    $pics[] = array('image_3', 'Third Alt', 'You can link in captions.');
?>

Then I write a little HTML and begin the code. This version doesn't employ a function because I don't have multiple return points. Really, I probably just wasn't in the mood that day - it could easily be written as one. The PHP here simply selects a random array from the $pics array and assigns it to the $pic variable.

<li class="sidebox">
    <h2>Random Snapshot</h2>
<?
    $random = rand(0, count($pics)-1);
    $pic = $pics[$random];

Since I haven't specified the height or width, and each image varies, I simply attain that value with PHP's built-in "getimagesize()" function.

    list($width, $height, $type, $attr) = getimagesize("/path/to/my/side/pictures/directory/".$pic[0].".jpg");

From there, we simply echo the appropriate information.

    echo '<p><img src="/imgs/pics/'.$pic[0].'.jpg" '.$attr.' alt="'.$pic[1].'" style="border: 1px solid #000;" /></p><p>'.$pic[2].'</p>';
?>
</li>

Enjoy. I probably won't have the time to support this code, but I may have time to answer some quick questions if you have them.

Also, to share this code, please link to this page. If you use the code, include the permalink to this page in the comments, both so you know where to look again if you have trouble and so you can tell anyone who asks you where you got the code where to look.

5 Responses to "WordPress Random Header Images"

  1. You could change /path/to/theme to <?php bloginfo('stylesheet_directory'); ?>. (Or get_bloginfo() to return it.) This just makes things easier if you move or otherwise.

  2. I've implemented a random header using the Random File plugin by Scott Reilly. I just pop a bunch of images in a folder and just set the DIV ID background to <?php echo c2c_random_file('/folder'); ?> Works a treat, and all I need to do to add more pictures is drop them into the folder

  3. [quote comment="39761"]You could change /path/to/theme to <?php bloginfo('stylesheet_directory'); ?>. (Or get_bloginfo() to return it.) This just makes things easier if you move or otherwise.[/quote]

    You're right, but you have to be careful about using it too much. It can't be used where I've written /path/to/my/side/pictures/directory/, for example, because that's an absolute path on the server. I also don't think it'll work very well in the included files.

    [quote comment="39767"]I just pop a bunch of images in a folder… all I need to do to add more pictures is drop them into the folder.[/quote]

    You can read above at least two or three reasons why that solution would be limiting to me.

  4. [...] you refresh the page.  I did this with the Random File WordPress plugin and a little help from NSLog(); to keep the code XML compliant by adding height and width [...]

  5. I've got the header to work. Thanks for the help! I would like to incorporate the special image on specific days on the sidebar. How can I modify the following code to allow me to return an array? Is it possible?

    switch(date('md'))
        {
            case '0101':
                return '_newyear'; break;
            case '0323':
                return '_birthday'; break;
            case '1031':
                return '_halloween'; break;
            case '1225':
                return '_christmas'; break;
            default:
                break;
        };