Musings about technology and other neat stuff

BrT random header image

How to display random header images in a Wordpress theme

November 3rd, 2008 · 8 Comments

I saw an article on 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):

$curdir=getcwd(); chdir(get_template_directory() . "/images/headers");
$files=glob("*.{gif,png,jpg,gif}", GLOB_BRACE);
<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.

Tags: · · ·

8 responses so far ↓

  • 1  jbj // Nov 3, 2008 at 6:47 am

    Nice code! I love how open source work: I developed a small code, you modify it your way :)

  • 2  nicoHO // Feb 1, 2009 at 12:07 pm

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

  • 3  zzamboni // Feb 1, 2009 at 11:01 pm

    I would say you can use exactly the same technique shown here, but insert the code in the place and format needed to replace the background image in the theme you are using.

  • 4  nicoHO // Feb 2, 2009 at 4:14 pm

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

  • 5  zzamboni // Feb 2, 2009 at 7:57 pm

    Great! Glad to see if works well.

  • 6  nicoHO // Feb 9, 2009 at 2:31 am

    Welcome to
    refresh to see:)
    Chinese content

  • 7  Riannarey // Apr 4, 2009 at 12:23 am

    i've looking this code for a week :D 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?? :D

  • 8  Hans // Jun 23, 2009 at 2:48 pm

    Great tips
    Thanks for share
    Very useful