2

I have been spending some time working with the new Rest API. I understand what it is doing but I don't understand how the JSON is used to actually display the content on a page.

I have been fooling around with example.com/wp-json/posts and I see all the code. I can even figure out how to filter them the way I want. What I can't seem to figure out is how do i display this content in a WP post or page?

example: I am using a multisite install and I would like to use 5 of the most recent posts from SITE A on SITE B but I don't understand how all that JSON code is edited and displayed.

I can't seem to find any beginning to end samples on this subject everyone just shows how you grab the content.

2

I will assume you want to use PHP to display this data directly using a template, there are alternatives such as using another language or actually creating posts via the API.

Simply put you want to take the JSON string and convert it into a PHP object or array using json_decode. http://php.net/manual/en/function.json-decode.php.

Once the JSON is stored as an object or array you would simply echo or do what you want with the data.

For example:

$json = '{"a":hello,"b":hi,"c":hey,"d":yo,"e":ola}';
$data = json_decode($json);
echo $data->{'a'}
// this should echo the value "hello"

It's important to note to cache external requests, you do not want to make a remote request each time the data is needed, rather you would use the Transient API with a set time for the data to expire and refresh.

Two other important links:
http://codex.wordpress.org/HTTP_API
http://wp-api.org/

  • Hi Wyck thanks. I am not using this live I am just trying to learn it.So doing this with RSS is still a better way? – milo99 Dec 7 '14 at 21:37
  • Better is subjective, it depends on your needs, in my opinion a REST API is certainly superior to an RSS feed, they are not really comparable, but this wasn't your original question. – Wyck Dec 7 '14 at 21:49
  • Np I actually phrased that wrong. I am going to edit my original question now that I have learned a few things based on your reply – milo99 Dec 7 '14 at 21:53
  • If the question is new , just close this one and create a new one please. – Wyck Dec 7 '14 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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