WordPress Tutorials

Several days ago, a friend of mine @arhamHaryadi asked me about how to make a random background which changes every time visitor visit / refresh the page. The answer is simple yet easy, use Matt Mullenweg’s randomimage script. Instruction of how to use it is pretty self-explanatory on that script. However, some of you probably want to use it on your theme. Here’s the quick how-to integrate it into your WordPress theme:

  1. Create a directory on your theme folder named randombg. Put all images you want to use as random background on this directory.
  2. Create a file named randomimage.php inside the freshly-created randombg directory. Copy and paste Matt’s randomimage script into that file.
  3. Open your theme’s functions.php file and paste these functions. Read the comment on the script for further explanation. Basically what these functions do are printing a stylesheet and hooking it into wp_head() theme hook.
    // Hooking ess_random_background() to wp_head()
    add_action("wp_head", "ess_random_background");
    
    // Printing random image background stylesheet. Random image calling is done by Matt Mullenweg's randomimage script
    function ess_random_background(){
    ?>
    <style type="text/css">
    body    {background:url(<?php bloginfo("stylesheet_directory"); ?>/randombg/randomimage.php);}
    </style>
    <?php
    }
    

That’s it. Pretty simple and easy to do, huh? This is the simplest way i know to create random background functionality to your WordPress theme. However, this trick has a downside: it has no back-end / dashboard interface so user should have an access to the FTP to put the image file on randombg directory. I’ve had a more manageable alternative than this, using WordPress custom post-type feature. I’ll discuss it on the next post. Stay tune on Outstando.

P.S.

I’ve made a twentyten child theme demo which uses this trick, just in case you want to see how does it actually work.

Download the file here.

5 thoughts on “WordPress Simple Random Background Using Matt Mullenweg’s randomimage script

  1. […] discussed about creating simple random background in WordPress, including its cons which has no back-end interface, on the previous post. Some people are okay […]

  2. setelah pencarian yang cukup lama, akhirnya ketemu juga plugin yang satu ini.
    Thanks 😀

  3. It works and was very easy. But it does not work in the Safari or Chrome browsers. Any thoughts on that?

  4. Thanks yo!

    tapi mana live demo-nya yak?
    Did you actually provide it or it’s just me who was not able to find it anywhere on your blog post?
    help! 😯

  5. thank you. this blog help me so much.

Share Your Thought