using wp_remote_get instead of file_get_contents [duplicate]

If you need to send a JSON response, then there’s a set of functions for that. In case you need that for an AJAX callback:

Would finally be something like that:

$request  = wp_remote_get( 'http://example.com' );
$response = wp_remote_retrieve_body( $request );
if ( 
    'OK' !== wp_remote_retrieve_response_message( $response )
    OR 200 !== wp_remote_retrieve_response_code( $response )
)
    wp_send_json_error( $response );

wp_send_json_success( $response );

Both wp_send_json_success/_error() functions are wrappers for wp_send_json(), which includes wp_die() at the end. So there’s nothing else to do.

Keep in mind that 99% of all remote APIs are sending 200/OK in case of errors. You’ll still have to manually inspect the result and check for errors.

Leave a Comment