I am using WP 4.6 which the rest api have not yet included in the core. But I still can use rest_api_init
to create an api endpoint. The problem is how can I change the endpoint response into proper json format?
This is what I did.
add_action( 'rest_api_init', function () {
register_rest_route( 'news/v1', '/latest', array(
'methods' => "GET",
'callback' =>'get_latest_posts_api',
) );
} );
function get_latest_posts_api($data ){
$data = array(
'title' => 'test title',
'content' => 'blah blah blah......'
);
return rest_ensure_response($data);
}
When I call the endpoint in another wp site, I got nothing.
$recent_posts = wp_remote_get("http://xxxx.com/wp-json/news/v1/latest/");
$i = 1;
print_r(json_decode($recent_posts['body'], true));//this give me nothing
echo $recent_posts['body']; //this give me the raw data though.
When I open directly on firefox, it shows me SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
What is the problem?
UPDATE
I added data array to be returned, but still got the error.
UPDATE
Debug using json_last_error()
on decoding the response and it gave me JSON_ERROR_SYNTAX
error. But I don't get it, I thought the register_rest_route
already handle converting to json?
I also tried with json encoding in the callback function, still got me this error.
I am lost.
body
? You probably should decode the whole JSON response and then echo what you need.$recent_posts
to your question can help us understand the problem better. Right now, it's unclear to me.