How to Use the WordPress HTTP API
Posted on July 15, 2011 in Wordpress
WordPress provides a way for developers to fetch other web pages. It’s called the HTTP API. If you’re using things like file_get_contents or some other PHP functions in your WordPress theme or plugin, you’re doing it wrong.
HTTP API Applications
You could use the HTTP API to…
- Interact with other APIs (facebook, twitter, etc)
- To screen scrape other sites or create some sort of aggregation site
- Create your own plugin repository
There are a lot of potential uses, but this tutorial will focus the first. We’ll create a shortcode that displays the number of likes a given Facebook page has.
Step 1: Registering the Shortcode
First we need to register the shortcode. This is done via the add_shortcode function. It takes too arguments: first, the name of the shortcode (the stuff between the square brackets) and a the call back function that displays the shortcode.
// Hook in after wordpress has started so the add_shortcode function is available
add_action( 'init', 'cdhttp_register_shortcode' );
function cdhttp_register_shortcode()
{
add_shortcode( 'fbcount', 'cdhttp_fbcount' );
}
Step 2: Displaying the Shortcode
Next we need to create a function with the same name as the second argument of add_shortcode call. This function gets passed up to three arguments, but we only need the first: the attributes passed into the shortcode. If we had this, [fbcount page="classicalguitarblog"], then page="classicalguitarblog" would be the attribute.
function cdhttp_fbcount( $atts )
{
extract(
shortcode_atts(
array(
'page' => 'classicalguitarblog'
),
$atts
)
);
// Make sure the $page attribute is clean
$page = esc_attr( strip_tags( $page ) );
}
shortcode_atts compairs an array of defaults and the actual atts passed into the shortcode. If any of the passed in attributes are not in the default array, they are removed. In other words, in the shortcode [fbcount page="classicalguitarblog" x="1213"], x=”1213″ would be removed by shortcode_atts because x is not a valid attribute (its not in the array of defaults).
If a user fails to specify one of the attributes, it will be replaced by the defaults.
Step 3: Actually using the HTTP API
Alright, with the housekeeping and shortcode creating out of the way, we can add some more stuff to our function that actually displays the Facebook count.
First we build a URL to pass into the http api function wp_remote_get. For this, we’ll use the facebook graph api. Since WordPress doesn’t handle https:// urls, we have to use the non-secure version of the graph api URL.
$url = 'http://graph.facebook.com/' . $page;
Now onto opening the page. We’ll use a function called wp_remote_get which, as the name implies, fetches the url passed in as its argument via a standard get request. wp_remote_get returns an associative array with the headers, response body, response codes and messages, and the cookies.
$response = wp_remote_get( $url );
By far the coolest part about the HTTP api is that if the GET request fails in some way, WordPress will return a WP_Error. Which means you can check for that via is_wp_error, and bail if something goes wrong. While we’re at it, we’ll also check to make sure the response was a 200 status code and the site loaded correctly.
if( is_wp_error( $response ) || $response['response']['code'] != 200 ) return;
So far, our shortcode function looks like this:
function cdhttp_fbcount( $atts )
{
extract(
shortcode_atts(
array(
'page' => 'classicalguitarblog'
),
$atts
)
);
$page = esc_attr( strip_tags( $page ) );
// Frist we construct a url for our wp_remote_get
$url = 'http://graph.facebook.com/' . $page;
// Fetch the page with wp_remote_get
$response = wp_remote_get( $url );
// Bail if wp_remote_get fails or the response code is anything but 200
if( is_wp_error( $response ) || $response['response']['code'] != 200 ) return;
When using shortcodes, your callback function does not echo anything out. Instead you have to return the values you wish to display. The Facebook Graph API returns a JSON, found at $response['body']; we’ll use the json_decode PHP function to interpret it. Then we’ll return the number of likes wrapped in a paragraph tag.
// Facebook returns a JSON, so let's decode it. the body of the page is in $response['body'] $body = json_decode( $response['body'] ); // Return out value! return '<p class="fb-count">' . $body->likes . ' Fans</p>';
Finally, our entire shortcode callback function:
function cdhttp_fbcount( $atts )
{
extract(
shortcode_atts(
array(
'page' => 'classicalguitarblog'
),
$atts
)
);
$page = esc_attr( strip_tags( $page ) );
// Frist we construct a url for our wp_remote_get
$url = 'http://graph.facebook.com/' . $page;
// Fetch the page with wp_remote_get
$response = wp_remote_get( $url );
// Bail if wp_remote_get fails or the response code is anything but 200
if( is_wp_error( $response ) || $response['response']['code'] != 200 ) return;
// Facebook returns a JSON, so let's decode it. the body of the page is in $response['body']
$body = json_decode( $response['body'] );
// Return out value!
return '<p class="fb-count">' . $body->likes . ' Fans</p>';
}
Wrap Up
You can download this code in the form of a plugin here. The HTTP API is much more than the simple example here. You can do just about anything with it: change the headers you send, make POST requests, use other functions that only retrieve the response body or headers, and more.
The bottom line: if your WordPress site or plugin is requesting data from an external URL without using the HTTP API, you’re doing it wrong.





