Recently I have been doing a lot of work with API’s and these often involve loading text content (rss/ xml/ json etc) from another website and then displaying the results – for instance the Twitter feed at the bottom of this website uses the Twitter Search API to get my latest updates.
There are all sorts of ways to access this data, but different servers require different methods so it’s good to have a generic method for accessing the data… and WordPress has one built in. Even better; it’s really easy to use.
WordPress Http – WP_Http
Below is a really basic usage for the plugin that will grab the 5 latest items from my Twitter stream and stick them in an array called $content. You can read up on the Twitter search API here.
$url = 'http://search.twitter.com/search.json?q=from%3Abinarymoon&rpp=5';
$request = new WP_Http;
$result = $request->request($url);
$content = array();
if (isset($result->errors)) {
// display error message of some sort
} else {
$content = $result['body'];
}
Other places this could be used include (but are not limited to):
- In my theme The Local I use it to grab the current weaterht for the specified location.
- In Accumulo it’s used to load the RSS feeds that you can see on the homepage.
- Many WordPress plugins use similar functionality to get data for other webservices such as loading Flickr galleries.
If you’re not using WordPress then you may find that using cURL or file_get_contents would be good alternatives to the WordPress HTTP API.
Is there anything else you can think of that this could be used for?
Was it good/ useful/ a load of old rubbish? Let me know on Mastodon, or BlueSky (or Twitter X if you must).
Link to this page
Thanks for reading. I'd really appreciate it if you'd link to this page if you mention it in your newsletter or on your blog.