GibsonFX
GibsonFX

Reputation: 1060

Random Content Script with Random Timed Delay

At the moment I have a really basic PHP script for randomly drawing quotes from a text file.

<?php include('testimonials.txt');
  srand ((double) microtime() * 100000);
  $random_number = rand(0,count($quotes)-1);
  echo ($quotes[$random_number]);
?>

Of course currently the script executes every time the page loads and brings up new content each time the page is refreshed.

I want to know is there any easy way to modify this to change the content on a timer, so it only changes once a day, or every few days?

If it requires altering the wp-cron.php of my site, any idea what I would need to put in there to do so?

Thank you

Upvotes: 0

Views: 407

Answers (2)

Jon
Jon

Reputation: 437366

You can start with something as basic as this, which saves the id of a quote and the time it was picked in a file:

<?php
$cachefile = './current_t_id';
$time = $id = null; // assume we have no cached quote
$change_every = 3600; // seconds
include('testimonials.txt');

// if cached quote exists, load it
if(is_file($cachefile)) {
    list($time, $id) = explode(' ', file_get_contents($cachefile));
}

// if no cached quote or duration expired, change it
if(!$time || time() - $time > $change_every) {
    srand ((double) microtime() * 100000);
    $id = rand(0,count($quotes)-1);
    file_put_contents($cachefile, time().' '.$id); // update cache
}

// echo the quote, be it cached or freshly picked 
echo ($quotes[$id]);

There are several things that can be improved here (e.g. error handling, the possibility of the testimonials file changing in a way that makes the cached quote invalid, etc) but the basic idea should be apparent.

Upvotes: 2

jli
jli

Reputation: 6623

You need to persistently store some variables, either in a database, flat file or somewhere else.

For example, you could store the time the quote was last updated, as well as the current quote id. When loading the page, you check if the time difference is greater than some amount of time (e.g. 1 day, 2 days etc) and if it is generate a new quote id. Otherwise, just get the current quote id and display it.

Upvotes: 0

Related Questions