-
-
Save slopesweb/d864c07ad51d52abb753af6a8da23659 to your computer and use it in GitHub Desktop.
Standard loop of posts using the WP REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Standard API query arguments | |
$args = array( | |
'orderby' => 'title', | |
'per_page' => 3 | |
); | |
// Put into the `add_query_arg();` to build a URL for use | |
// Just an alternative to manually typing the query string | |
$url = add_query_arg( $args, rest_url('wp/v2/posts') ); | |
// A standard GET request the WordPress way | |
$stuff = wp_remote_get($url); | |
// Get just the body of that request (if successful) | |
$body = wp_remote_retrieve_body($stuff); | |
// Turn the returned JSON object into a PHP object | |
$posts = json_decode($body); | |
?> | |
<?php // Standard foreach loop. Essentially, we just used the WP REST API to do the same thing as get_posts() ?> | |
<?php if (!empty($posts)) : ?> | |
<?php foreach ($posts as $post) : ?> | |
<article <?php post_class(); ?>> | |
<h1><?php echo $post->title->rendered; ?></h1> | |
<div><?php echo $post->content->rendered; ?></div> | |
</article> | |
<?php endforeach; ?> | |
<?php endif; ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment