public
Created

Using get_transient and set_transient to save changing data

  • Download Gist
WP-Transient-API.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
<?php
 
//let's get my klout score!!
 
//first, let's see if I've got the data already cached locally
$klout = get_transient("klout");
//dang it! it looks like I might not. let's check with the Klout API
if( !$klout ) {
$json = file_get_contents("http://api.klout.com/1/klout.json?key=[API key]&users=clarklab");
$return = json_decode($json, true);
$kloutscore = $return["users"][0]["kscore"];
 
//if the Klout API gave us a score, let's save it!
if( $kloutscore ) {
//in a field named "klout", we'll save our $kloutscore, for 12 hours (60 seconds x 60 minutes x 12 hours)
set_transient("klout", $kloutscore, 60 * 60 * 12);
 
//let's also make sure to set the data you were originally looking for
$klout = $kloutscore;
}
}
echo 'Now I can safely check my '.$klout.' score with transients!';
 
?>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.