WordPress HTTP API

Welcome to the first in a series of articles on APIs provided by the WordPress core. Each article will document and hopefully explain how to use the features provided by WordPress to save you writing unnecessary code.

The HTTP API

Many plugins and themes require access to remote files, be that tweets from Twitter or images uploaded to a server. And for the vast majority of these cases developers write their own URL wrapper functions, using cURL, file_get_contents or other such functions. Unfortunately this means that each developer must also handle all of the issues this can bring including checking the libraries are enabled, remote file access is allowed etc.

Wouldn’t it be great if WordPress just provided a way to get a file and have all of those issues be dealt with for you? Wish no more, since WordPress 2.7(!) has had an HTTP API that provides a set of simple functions to request remote data.

The main function we’re going to be looking at today is wp_remote_get(). As its name implies, this function GETs a file and returns it. There are others, such as wp_remote_post() which performs a POST request, but GET is the easiest to demonstrate and the most frequently used.

Here’s an example of getting the homepage of this blog:

[php]
<?php

$url = ‘http://hybridlogic.co.uk’;

$response = wp_remote_get($url);

if(!is_wp_error($response)) {
echo wp_remote_retrieve_body($response);
} else {
echo ‘An error occurred getting page.’
}

?>
[/php]

  1. The first thing we do is call wp_remote_get() passing it the URL of the file we wish to access. You can also specify an array of headers to send alongside the request.
  2. If the page failed to load, it will return a WP_Error object. We use is_wp_error() to make sure we have a valid response and not an error in this case.
  3. Finally, we use wp_remote_retrieve_body() to extract the text of the actual page. This function provides a nice wrapper for the $response array, but you don’t have to use it.

And in it’s simplest form, that is the WordPress HTTP API. The advantage of using this compared to writing your own URL wrapper is the simplicity and flexibility afforded to you. WordPress can decide on the best transport to use, and handles all errors gracefully. The data returned can be quickly checked before being passed off to SimpleXML, a thumbnail resizer or any number of other options.

There will be times however when using the HTTP API is not the best solution to your problem, for instance making multiple calls with PHPs multi_curl functions. For all other uses though, it’s more trouble than it’s worth to not use the HTTP API.