1

I want to get a random background image using php. Thats done easy (Source):

<?php
  $bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' );
  $i = rand(0, count($bg)-1); 
  $selectedBg = "$bg[$i]"; 
?>

Lets optimize it to choose all background-images possible inside a folder:

function randImage($path)
{
    if (is_dir($path)) 
    {
        $folder = glob($path); // will grab every files in the current directory
        $arrayImage = array(); // create an empty array

        // read throught all files
        foreach ($folder as $img) 
        {
            // check file mime type like (jpeg,jpg,gif,png), you can limit or allow certain file type   
            if (preg_match('/[.](jpeg|jpg|gif|png)$/i', basename($img))) { $arrayImage[] = $img; }
        }

        return($arrayImage); // return every images back as an array
    }
    else
    {
        return('Undefine folder.');
    }
}

$bkgd = randImage('image/');
$i = rand(0, count($bkgd)-1); // while generate a random array
$myRandBkgd = "$bkgd[$i]"; // set variable equal to which random filename was chosen

As I am using this inside a wordpress theme, I need to set the $bkgd = randImage('image/'); relative to my theme folder. I thought, I could do that using:

$bgfolder = get_template_directory_uri() . '/images/backgrounds/';
bkgd = randImage($bgfolder);

When I test $bgfolder, which seems to be the most important part, using var_dump() I receive a not working path:

http://yw.hiamovi-client.com/wp-content/themes/youthwork string(19) "/images/backgrounds"

Somehow there is a space before the /images/backgrounds/. I have no idea where this comes from! …?

1 Answer 1

2

You'll want to change

$myRandBkgd = "$bkgd[$i]";

to

$myRandBkgd = $bkgd[$i];

If that doesn't help, use var_dump() instead of echo() to dump some of your variables along the way and check if the output corresponds to your expectations.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot for your effort! Both does not help. My output is at follows http://pathtotheme.de/wp-content/themes/mytheme string(1) "U"
Well, throw a couple var_dump()s into your code – i.e. before return($arrayImage) – and look for yourself ;)
Thats a smart trick to find errors! Currently the whole function returns Undefine folder., because my path is not correct. Testing it using <?php var_dump($bgfolder) ?> shows, that there is a space coming out of nowhere. I have edited my question and added this detail!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.