Random Full-Size BG Image Code for plugin creation
-
I asked this on StackOverflow as well and haven’t received an answer.
I’m having an issue creating a full screen background for my WordPress theme that uses random images from the image library. I want to write a PHP function that can be used on multiple sites, so I can’t simply use the direct path in the code. It also needs to work on MultiSite in such a way that it only pulls images that are uploaded to that site. Here’s the code I’m working with:
HTML for my Background Div<div id="background" class="background" style="background-image:url(<?php displayBackground();?>);"> </div>
PHP to randomize my image folder
<? php function displayBackground() { $uploads = wp_upload_dir(); $img_dir = ( $uploads['baseurl'] . $uploads['subdir'] ); $cnt = 0; $bgArray= array(); /*if we can load the directory*/ if ($handle = opendir($img_dir)) { /* Loop through the directory here */ while (false !== ($entry = readdir($handle))) { $pathToFile = $img_dir.$entry; if(is_file($pathToFile)) //if the files exists { //make sure the file is an image...there might be a better way to do this if(getimagesize($pathToFile)!=FALSE) { //add it to the array $bgArray[$cnt]= $pathToFile; $cnt = $cnt+1; } } } //create a random number, then use the image whos key matches the number $myRand = rand(0,($cnt-1)); $val = $bgArray[$myRand]; } closedir($handle); echo('"'.$val.'"'); }
I know that my CSS markup is correct because if I give the DIV a fixed image location, I get a fullscreen image. Can anyone tell me what to do to fix it?
Also, I’m doing it this way because I don’t like the way the WPSupersize.js script affects the site styling.
- The topic ‘Random Full-Size BG Image Code for plugin creation’ is closed to new replies.