1

I'm getting familiar with the WP REST API 2 plugin and I started following the amazing directions from Torque's Guide.

Everything seems pretty clear but I'm having trouble understanding this error (Keep in mind I've follow and reviewed all directions step by step. Here is the function I'm using:

$url = 'http://rbm.dev/wp-json/wp/v2/works/53';

$response = wp_remote_get( $url );

function slug_get_json( $url ) {
    //GET the remote site
    $response = wp_remote_get( $url );
    //Check for error
    if ( is_wp_error( $response ) ) {
        return sprintf( 'The URL %1s could not be retrieved.', $url ); //get just the body
        $data = wp_remote_retrieve_body( $response );
    }
    //return if not an error
    if ( ! is_wp_error( $response ) ) { //decode and return
        return json_decode( $response );
    }
}

I can easely see the JSON object if accesed through a restful client such as PAW or directly from the browser. But the function is returning this:

Warning: json_decode() expects parameter 1 to be string, array given...

I'm understanding the logic of the function but since I'm so new to this I'm not certain about the error. Not sure why json_decode() is not receiving the data as it's supposed to do. Keep in mind this is exactly from the Torque's book -- is there a mistake in the syntax of the function?

Thanks!

1 Answer 1

2

wp_remote_get return array of results containing keys body, headers, response etc depending on arguments.

And json_decode only accept JSON string. So correct your code in this way

//return if not an error
    if ( ! is_wp_error( $response ) ) { //decode and return
        return json_decode( wp_remote_retrieve_body( $response ) );
    }

Ref: Return Values of wp_remote_get or wp_remote_post

2
  • Thank you! this makes sense -- Do you think that is an error in the publication? From the author referring to that snippet: Although you can get the body directly using wp_remote_retrieve_body(), this is a bad idea because, if something was wrong with your request or the server making the request, it could be a WP_Error instead of the actual response you need.
    – mmarquez
    Commented Feb 24, 2016 at 16:39
  • @mmarquez I am not sure about the book, we follow codex because we can see it and we can edit it. We are already checking ! is_wp_error( $response ) so it will not go inside the if block if something goes wrong in WordPress and wp_remote_retrieve_body also check for the same. On other hand for server errors you can check header status code to handle 400, 500 errors!
    – Sumit
    Commented Feb 24, 2016 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.