Вопрос

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!

Это было полезно?

Решение

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с wordpress.stackexchange
scroll top