I’m using the following code to generate a random background image on a specific css element in my WordPress Theme. It works fine but loads a new background every pageload.(i’m using the “NextGEN Gallery” to upload the backgrounds in the right folder without the need of ftp.

// Set up
$imgFolder = "/wp-content/gallery/achtergronden/"; // the path from the sites root to the image folder created at 3 above
$element = "rest-wrapper"; // the css ID of the element to apply the background image to
// That's it!! Nothing below this line needs to be changed
$img = null;
// build up the path to the image folder
if (substr($imgFolder,0,1) != '/') { $imgFolder = '/'.$imgFolder; }
if (substr($imgFolder,-1) != '/') { $imgFolder = $imgFolder.'/'; }
$path = $_SERVER['DOCUMENT_ROOT'] . $imgFolder;
// populate an array to hold valid file type extensions
$extList = array('gif','jpg','jpeg','png');
// create an array to hold the list of image files
$fileList = array();
// open a handle to the directory
$handle = opendir($path);
// loop through the contents of the directory
while ( false !== ( $file = readdir($handle) ) ) {
    // get the info for each file
    $file_info = pathinfo($file);
    // check that the file in in the allowed extensions array
    if ( in_array( strtolower( $file_info['extension'] ), $extList)    ) {
        // add the file to the array
        $fileList[] = $file; }
    // close the handle to the directory
    // if we have at least 1 file in the list
    if (count($fileList) > 0) {
        // select a random index from the file list array
        $imageNumber = time() % count($fileList);
       // assign the filename for that array index to the $img var
       $img = $imgFolder . $fileList[$imageNumber];
       $css = "#$element { background-image: url('".$img."');
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
    }@media screen and (max-width: 960px) {
       // tell the browser what we're sending
       header('Content-type: text/css');
       // and write out the css
       echo $css;

How do i change this code (php) to only load a new background each time a visitor visits the website? (a random background every day would also be acceptable).

Read more here: How do i add a random background image on a specific element each session?


If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Related Wordpress search:

, , , , , ,

Wordpress related questions and answers: