Support » Fixing WordPress » Random background image

  • This thread has a great tip for using random background images. The topic is marked “resolved” but I have a question about it. I don’t know how to make it “unresolved” since I am not the original poster.

    I don’t know the etiquette for this so I’m just going to post two quick excerpts from the thread:

    Original question: I would like to place a random background image function on my main wordpress page so that each time the user visits the blog or refreshes the page, a random background image appears on the entire page.

    simple HTML, but adjust to what you need inside your header.php file


    Matt of wordpress fame! has an example here:

    This is great code. Simple & elegant.

    I do have one question on implementation.

    I am rotating the background image for the pages.

    However, I want to use a different random background image on the index.php and single.php templates. I am using the same code to get the image in each file

    <style type="text/css">body {
    	background-image: url(../../../images/backgrounds/rotate.php);

    However, when I go from page to page my FireFox cache is loading the same background image instead of getting a new one (Internet Explorer 7 seems to load it new each time). If I <shift>+”Refresh” I get a different background each time but unless I do the force refresh each page loads with the cached background.

    Is there a good way to work around this?

    I assume I can use a different “random image” directory for each template and since I would call the random image from a different place there would not be the same one in the cache, but that seems very clunky.

    Any ideas?

Viewing 15 replies - 1 through 15 (of 15 total)
  • Bump

    In my opinion this is the worst way to do random images.

    In the worst case scenario, the filename is cached and you never get a random image. In the best case your file is never cached, so you have to download it all time — either way its horrible.

    If your server supports ‘glob’ you can do this:

      $backgrounds = glob('path/to/images/*.jpg');

    that reads the paths to a directory full of jpegs into an array, then shuffles the array.

    to retrieve a random path after the array has been shuffled, just use <?php echo $backgrounds[0] ?> wherever you want your path to appear.

    Why is this better? — glad you asked.

    This way uses the proper filename to the file each time, instead of masquerading as an image with the name “random.php”

    This allows your users to cache EACH of the random backgrounds, so that on their next visit, they will load from cache much more quickly.

    If you want to play with this you can see it in action in my header. Hit reload a few times… Once a header is downloaded once, it doesn’t need to be freshly downloaded each time it’s displayed.

    Hello Ivovic,

    sounds like you have a much better solution, i’m interested in trying your script on my blog… just not sure where this needs to be placed, in the index.php ? i’m pretty new to wordpress and php so am not sure about what glob is…

    my wordpress is here:

    yr help is appreciated!

    i found a helpful article which did the trick for me:

    the actual code is from here:

    got it working on my page, looks great!

    Hi – I’m also new to wordpress and am interested in emulating a site I had years ago. Mainly I want to have a changing / rotating background image – but I would like it to update periodically – say every 10 seconds. Is there an easy way to use some of the code about with a little modification to make this happen? Many thanks in advance….


    Hey all,

    Having a bit of trouble using any of these scripts.

    I’m trying to have a rotating bg image (about 3 or 4 of them).

    Currently my css looks like this:

    body {
    background: #261706 url(img/bg.jpg) no-repeat center top;
    font:75% verdana, arial, helvetica, tahoma, sans-serif;
    line-height: 18px;

    I changed it to

    body {
    background: #261706 url(rotate/rotate.php) no-repeat center top;
    font:75% verdana, arial, helvetica, tahoma, sans-serif;
    line-height: 18px;

    But no luck.

    Of cxourse I’ve uploaded and modified the rotate.php file but to no avail.

    Perhaps someone out there has had better luck than I?

    Any help would be appreciated!

    After some trial and error had some great luck with this code!!

    Random Image Script

    Based on Ivovic’s suggestion, this is what I did and it’s working for me. Of course, if your server *does not* support glob this will not work. And aside from trial and error, I’m not exactly sure how to tell if your server does.

    // Header rotation script based on suggestions found in this thread:
    $backgrounds = glob('/var/www/html/*.jpg');
    // Glob seems to need the full path to the target folder. Site root just wasn't working.
    shuffle($backgrounds); // Shuffle the folder contents.
    $string = $backgrounds[0]; // Pick one image.
    // Now delete the parts of the path before the site root.
    $pattern = "@/var/www/html/";
    $replacement = "";
    $newString = preg_replace($pattern, $replacement, $string);
    // And finally output the styles needed to place a background image in the header.
    echo "<style type='text/css'>\n";
    echo "#header {background: url('".$newString."') no-repeat top left;}\n";
    // Obviously, if your header doesn't use "header" as its CSS id, you will need to change that.
    echo "</style>";

    This goes in the head of your header.php file.


    If anyone is still looking for something to handle random header images, be it a background of an actual IMG tag, i’ll be posting up some free theme functions for anyone to use soon…

    Little more testing to be done, but looking good…

    Free, open code for anyone…

    EDIT: fixed problem.

    Take a look at what i posted here…

    You should be able to adapt it to your needs if you know code ok.

    If you still get stuck give it a few days and you can try one of the functions i’ll be posting… 😉

    Here is a dramatically simple, astonishingly clean solution to pretty much every issue mentioned on this page.
    There is no need for wordpress functions, arrays, complicated code editing, rotator.php files or ANYTHING. It also avoids having to manually <shift>+”Refresh” to load a new background image.

    Here it is – to use, simply put the div ID and image folder paths for your site inside this:….

    <div id="anyID" style="background:url(/yourimagefolderpath/<?= "img".rand(0,50).".jpg"; ?>) no-repeat left top;"> Your site text or other content </div>

    0,50 in the code only means it will show up from img0 to img50.jpg at random, in the final url produced by the php snippet. if you have only 5 image files, replace 0,50 with 0,4

    (Also, i think If you dont want ‘img’ as a prefix, just leave it empty. It should work.)

    It works beautifully – This is free of any page-caching issues, since the url changes each time the page is called, and the page is reloaded since it has changed since the last time.The more images you have, the more ‘random’ it is.

    I found this great solution by a google search for ‘random css background’, on the ‘page 2 results’ 🙂 . Am sharing it here in case anyone finds it useful, and this thread can be hopefuly closed.

    Not sure if it rings true for array_rand to, but the rand function is not reliable in terms of grabbing a realistic random…

    You’ll find this if you check the PHP site regarding the rand function at least…

    If you grabbed lets say a number from 1-5….

    You expect a success rate of 20% for each number, 1,2,3,4 and 5…

    However that’s not the case and why i explicitly avoided using rand() when i wrote a function. Of course the same issue may exist with array_rand, but i havn’t tested it extensively to know whether that’s true.

    NOTE: I refer of course to my second function… (click my name to see the functions). The first did use rand();, which as mentioned is not reliable..

    Hi t31os,

    As a WordPress novice, my php knowledge is quite zero. I use what works most easily, and this does the job pretty much all of the time.

    Working with just 4 images, i did notice the randomness was not even across all 4 images, as you say.

    However, i expect with more images, as i add them, it will even out. Also, this amount of randomness is ‘ok’ given the site requirement.

    Its not mathematically exact, but its essentially functional.
    Given its ease of use, which is most important, I can live with it.

    A better, perfect solution is always welcome, of course. Where would the rest of us be if others like you did’nt get deep into the details, and show the way.


    I’m not meaning to suggest it’s a huge problem, it depends on how fussy you want to be with the code…

    I’d personally use something like the time to change the image, that way it’s always reliable and the same, and in a defined sequence…

    Totally depends what you want to archieve…

Viewing 15 replies - 1 through 15 (of 15 total)
  • The topic ‘Random background image’ is closed to new replies.