Fetching GET post output in JSON objects

So far, we have seen how to GET posts and JSON objects. The preceding queries are sufficient to fetch (or GET) data for you, but how will you output the posts?

In WordPress, we often output posts by using the get_post() function that uses the global $post object. In a similar manner, we can use a loop that runs through all the posts retrieved by REST API and outputs them accordingly. For example, consider the following code:

$url = add_query_arg( 'per_page', 10, rest_url() ); $posts = get_json( $posts ); if ( ! empty( $posts ) ) { foreach( $posts as $post ) { ?> <article id="<?php echo esc_attr($post->ID ); ?>"> <h1><?php echo $post->title; ?></h1> <div><?php wpautop( $post->content ); ?></div> </article> ...

Get Learning WordPress REST API now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.