How to: Display a random header image

November 1, 2008 at 7:58 am

A lot of WordPress users seems to be very interested by being able to display a random header image. So, here’s a simple recipe, using the php rand() function, to display a random header on each post or page.

To achieve this recipe, we will use the php rand() function, which allows us to get a random number between 1 and 99 (in this exemple).
If the random number is less than or equals to 33, the first header image will be displayed. Less than or equals to 66, the second header image will be shown, and same for the last one, which will be displayed only if our random number and less than or equals to 99.

Paste the following code in your header.php file:

<?php
$result_random=rand(1, 99);

if($result_random<=33){ ?>
    <div id="header" style="background:transparent url(images/header1.png) no-repeat top left;">
<?php }

elseif($result_random<=66){ ?>
    <div id="header" style="background:transparent url(images/header2.png) no-repeat top left;">
<?php }

elseif($result_random<=99){ ?>
    <div id="header" style="background:transparent url(images/header3.png) no-repeat top left;">
<?php } ?>

<!-- Header code goes here -->
</div>