How to display random header images in a WordPress theme

I saw an article on wprecipes.com describing how to display a random header image in a WordPress blog. While the code shown works, it is a bit verbose and hard to maintain, so I thought I’d show how the random image in the header of this blog is done.

Note: you may need to adjust some of this to the specifics of the theme you are using, but the base mechanism is the same.

In this technique, the assumption is that you have a directory with header images, located in images/headers under your theme directory (e.g. /your/blog/directory/wp-content/themes/yourtheme/images/headers/). The code shown below will choose an image at random from this directory. The images should already have the appropriate size/ratio to be shown in your blog.

Here’s the code, to insert instead of the existing <img> tag for your theme’s header image (most likely in header.php):

<?php
$curdir=getcwd(); chdir(get_template_directory() . "/images/headers");
$files=glob("*.{gif,png,jpg,gif}", GLOB_BRACE);
chdir($curdir);
$file=$files[array_rand($files)];
?>
<img src="<?php echo(get_bloginfo('template_url')."/images/headers/$file"); ?>" width="770" height="140" alt="<?php bloginfo('name'); ?> random header image" />

Some things you may want to change:

  • The location of your images (if not under images/headers in your theme directory)
  • The size of the header images in the img tag
  • The filter for the images in the glob statement (currently it will grab any gif, png, jpg or gif files in that directory)

I’m not an expert PHP developer, so there may be a more efficient way of getting a random file from a directory, I’d be happy to learn about it.

Advertisements

8 responses to “How to display random header images in a WordPress theme

  1. Nice code! I love how open source work: I developed a small code, you modify it your way šŸ™‚

  2. Thank! I would like to ask how can a random picture as a background? Please check my WP.

  3. Thank! zzamboni
    I have the background of the successful implementation of a random switch!

  4. Welcome to
    http://www.nicoho.com/wp/?p=68
    refresh to see:)
    Chinese content

  5. i've looking this code for a week šŸ˜€ thanks, i'm very need it
    i'll try it and if i've some problem when i install it, can i ask you to solve the problem?? šŸ˜€

  6. Great tips
    Thanks for share
    Very useful

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s