Simple Function Using wp_remote_get()

There isn’t a good amount of information on wp_remote_get() in the codex. Take a look to see what I mean: https://codex.wordpress.org/Function_Reference/wp_remote_get After you’ve used the function, the information it returns also has to be formatted in a certain way or you won’t be able to do anything with it.

wp_remote_get() Basics

Let’s start with a simple function:
$response = wp_remote_get( 'http://yoursite.com/api/somecallhere' );
if ( is_wp_error( $response ) ) {
   echo 'There be errors, yo!';
} else {
   echo 'It worked!';
}
With this function, we’re using wp_remote_get() to retrieve our URL. If there’s an error, we display the first sentence. If it worked, we display the second sentence. Not much value in that so we need a few more lines of code.

What Comes Next?

Once we retrieve data from the URL, we need to format it correctly.
$response = wp_remote_get( 'http://yoursite.com/api/somecallhere' );
if ( is_wp_error( $response ) ) {
   echo 'There be errors, yo!';
} else {
   $body = wp_remote_retrieve_body( $response );
   $data = json_decode( $body );
}

if ( $data->Data ) {
   echo 'We got data, yo!';
}
After we retrieve our data, we use wp_remote_retrieve_body() and json_decode() to process it and get what we need. We can even go one step further and display our data.
$response = wp_remote_get( 'http://yoursite.com/api/somecallhere' );
if ( is_wp_error( $response ) ) {
   echo 'There be errors, yo!';
} else {
   $body = wp_remote_retrieve_body( $response );
   $data = json_decode( $body );
}

if ( $data->Data ) {
   print_r( $data->Data );
}
This we’ll display the array of data that was returned.

Conclussion

When you need to hook into an API or retrieve data from a URL, wp_remote_get() is the function you need. Just remember that you’ll also have to take a few more steps in order to get to the actual data you want. If you have any questions or feedback on this post, please use the comments below to start a discussion.

Small Biz Website Tips Newsletter

Stay up to date with the latest marketing, sales, and service tips and news.