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.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie