Created
January 30, 2013 20:00
-
-
Save clarklab/4676315 to your computer and use it in GitHub Desktop.
Caching a simple API call using the WP Transient API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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