How to Display Random Images as a Background in WordPress

If most of the content on a site is text, not many people will be eager to read it. Adding some images can make the layout feel much more lively right away. But creating custom images for every page is not easy, and that is where random background images can save time. This article introduces a simple way to display random background images in WordPress.

Step 1: add the following code at the top of the page where you want the background image to appear.

Before adding the code, make sure the image files referenced in the code have already been uploaded to the server.

<?php
    $bg = array('background01.jpg', 'background02.jpg', 'background03.jpg', 'background04.jpg', 'background05.jpg', 'background06.jpg', 'background07.jpg' );
 
    $i = rand(0, count($bg)-1);
    $selectedBg = "$bg[$i]";
?>

Step 2: use the randomly selected image as the background for an HTML element.

<style type="text/css">
    body{
        background: url(images/<?php echo $selectedBg; ?>) no-repeat;
    }
</style>

The code above is pure PHP and does not use any WordPress-specific functions, so in theory it can also be used in other PHP applications.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *