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.
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/