Skip to content

Instantly share code, notes, and snippets.

@clarklab
Created January 30, 2013 20:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save clarklab/4676315 to your computer and use it in GitHub Desktop.
Save clarklab/4676315 to your computer and use it in GitHub Desktop.
Caching a simple API call using the WP Transient API
<?php
//let's get some tweets!!
//first, let's see if I've got the data already cached
$tweets = get_transient("tweets");
//dang it! it looks like I might not. let's grab some tweets from the Twitter API
if( !$tweets ) {
$json = wp_remote_retrieve_body( wp_remote_get('http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=clarklab&count=5') );
$tweets = json_decode($json, true);
//if the Twitter API gave us some tweets, let's save them!
//in a field named "tweets", we'll save our $tweets, for 15 minutes (60 seconds x 15 minutes)
set_transient('tweets', $tweets, 60 * 15);
}
// now you can do stuff with your returned (or cached) data!
if ($tweets){
foreach ($tweets as $tweet) {
// do stuff
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment