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?


I added data array to be returned, but still got the error.


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.

  • Do you need to decode the body? You probably should decode the whole JSON response and then echo what you need.
    – Johansson
    Sep 1, 2017 at 7:43
  • @JackJohansson I tried, nothing come out.
    – dev-jim
    Sep 1, 2017 at 7:51
  • Adding the content of $recent_posts to your question can help us understand the problem better. Right now, it's unclear to me.
    – Johansson
    Sep 1, 2017 at 8:09
  • @JackJohansson, I added sample data in the endpoint function, still got the error.
    – dev-jim
    Sep 8, 2017 at 6:40
  • No I meant add the content of that variable to your "question", by using the edit link so we can investigate the issue.
    – Johansson
    Sep 8, 2017 at 7:04

1 Answer 1


Turn out it is caused by a BOM character from one of my included file. If you are having same problem, you can save your file to Encode in UTF8 without BOM.

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.