WordPress HTTP Request Class

Many WordPress plugin and theme developers eventually find the need to have their application make HTTP requests to a remote server. One example would be to make calls to the Twitter API, which involves making GET and POST requests and collecting the XML/JSON response.

There are many ways to make HTTP requests with PHP, such as cURL or fopen(), but the problem is that not everyone has the same server configuration. Some users may not have cURL installed, others may have fopen() or file_get_contents() disabled by their host. How do you find a solution that can accommodate everyone? You could write a set of functions that check to see which HTTP request components are available and then choose one to make the request. Or you could take the easy route and use the handy class built into WordPress.

The WP_Http class is an easy way to avoid the rigamarole and get back to the fun part of programming. It serves as a wrapper to separate the how from the equation, creating an abstract device to handle the requests.

$url = 'http://search.twitter.com/search.json?q=from%3Aredwall_hp&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'];

After Ben Gillbanks’ post pointed this class out to me, I did some searching and found Ozh’s more in-depth post, which shows how to send POST requests and HTTP headers.