How to change from “file_get_contents” to “wp_remote_get”

First, there is no error checking on any of the code, both the file_get_contents code, and the wp_remote_get code. Don’t just assume it worked, check!

$response = file_get_contents( "http://www.geoplugin.net/json.gp?ip=" . $ip_address);
if ( false === $response ) {
    // it failed, abort!

Three steps, first, make the request:

$response = wp_remote_get( $url );

Note that we aren’t using esc_url_raw, escaping is for enforcing assumptions on output, this is not browser output. If needed, use urlencode on the IP.

Then, we want to perform error checking. Your code performs no error checking of any kind, even in the file_get_contents example, it just assumes it worked. This is incorrect. Don’t just assume functions work, check for error values.

So before we use the result:

if ( is_wp_error( $response ) ) {
    // it's an error! Abort!

Here we can look at the error message in the response object to see what went wrong. Take a look at the WP_Error documentation for how to do that.

Then, look inside the $response to see what the result was. $response contains several items:

  • ‘headers’ (string[]) Array of response headers keyed by their name.
  • ‘body’ (string) Response body.
  • ‘response’ (array) Data about the HTTP response.
  • ‘code’ (int|false) HTTP response code.
  • ‘message’ (string|false) HTTP response message.
  • ‘cookies’ (WP_HTTP_Cookie[]) Array of response cookies.
  • ‘http_response’ (WP_HTTP_Requests_Response|null) Raw HTTP response object.

So to check what the HTTP response code is:

echo $response['code'];

Here, you want the body, and to make it easier, wp_remote_retrieve_body

$body = wp_remote_retrieve_body( $result )
// or..
$body = $result['body'];

Then we can json_decode. Note that I did not nest the function calls, that would make it really difficult to debug, and impossible to perform error checks.

Don’t forget that json_decode needs error handling too! Don’t just assume it worked.