I need to get 15 random images from a folder and show them on a page:
I tried the following code, however it did not do what I wanted:
$string =array();
$filePath='wp-content/themes/tema/img-test/';
$dir = opendir($filePath);
while ($file = readdir($dir)) {
if (eregi(".png",$file) || eregi(".jpg",$file) || eregi(".gif",$file) ) {
$string[] = $file;
}
}
while (sizeof($string) != 0){
$img = array_pop($string);
echo "<img src='$filePath$img' width='100px'/>";
}
So, you have all the files in
$string
array, that’s good.You can either use the
rand()
function to get some random integer in the arrays size:You would have to loop that.
Or, you could use
array_rand()
which will automate all that:You could do this using the
glob()
function native to PHP. It will get all files in a directory. Following that you can pick one file from the retrieved list.Use this code. Your random image will be available in $arRandomFiles.
Simple function that handles that
You can try function like: