0

I am trying to give my wordpress site a randomly pulled "About the Author" image in my footer.

My first solution was to create an array, name them each aboutAuthor[x].jpg and generate a random number for x. That works just fine, but I was looking for a solution that didn't involve me having to rename files and adding a line of code every time I decide to add a new image to the folder.

I found a solution on this site: http://photomatt.net/scripts/randomimage

He provides some php code

<?php

$folder = '';

$exts = 'jpg jpeg png gif';

$files = array();
$i = -1;
if ('' == $folder)
    $folder = './';

$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
    foreach ($exts as $ext) {
        if (preg_match('/\.' . $ext . '$/i', $file, $test)) {
            $files[] = $file;
            ++$i;
        }
    }
}
closedir($handle);
mt_srand((double) microtime() * 1000000);
$rand = mt_rand(0, $i);

header('Location: ' . $folder . $files[$rand]);
?>

Then I simply place that php file in the directory in question and call it in place of an image

<img src="/imgDirectory/rotate.php">

The only problem with this is that my browser is caching the resulting random image. With a normal reload or clicking a link to a new page, I get the same image. With a hard reload, I get a new one, like I want.

Oddly, in the sample on his website, it works as expected with a normal reload.

So what is the best way to achieve what I'm looking for?

Manzolo
  • 1,909
  • 12
  • 13
  • Set caching headers in your PHP script that tell the browser not to cache the file. See the linked thread for how to do that. – ceejayoz Sep 05 '19 at 20:11

1 Answers1

-1

Here is the solution

1) Create new div:

<div class="randomAuthor" id="randomAuthor"> </div>

2) Move image source

<img src="/imgDirectory/rotate.php">

to a separate PHP or html file, example author.php:

3) Load author.php into div "randomAuthor" using ajax code:

       $(document).ready(function(){   
 $('#randomAuthor').load("author.php");
});

This way on each refresh the $(document).ready(function(){..... will get triggerd which in turn will trigger rotate.php file thus you will get new image each time you open your page or refresh it.

Akash
  • 59
  • 6