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> <?php } //foreach }
Looking at the outcome of this loop when used within a standard function, this...