View posts and featured image using REST API Wordpress

1

I want to display the last two posts of Wordpress using API Rest, after a lot of research and test I can do this gambiarra there, but after I put this foreach inside the other it was kind of slow, it would be nice if I could show the images of each posts without needing a new foreach.

Can you simplify this code?

<?php
    $posts = file_get_contents('http://localhost/noticias/wp-json/wp/v2/posts?_embed=true?per_page=2');
    $obj = json_decode($posts);
    foreach ($obj as $post) {
        echo '<div class="posts">';

        $id = ($post->id);
        $thumbnail = file_get_contents('http://localhost/noticias/wp-json/wp/v2/media?parent=' . $id . '');
        $images = json_decode($thumbnail);
        foreach ($images as $image) {
            echo '<img src="' . $image->media_details->sizes->medium_large->source_url . '"/>';
        }
        echo '<h2><a href="' . $post->link . '">' . $post->title->rendered . '</a></h2>';
        echo '<p>' . $post->excerpt->rendered . '</p>';
        echo '<p>' . $post->date . '</p>';

        echo '</div>';
    }
    ?>
    
asked by anonymous 19.07.2017 / 03:31

1 answer

0

You can do this:

<?php
    $posts = file_get_contents('http://localhost/noticias/wp-json/wp/v2/posts?per_page=2');
    $obj = json_decode($posts);
    foreach ($obj as $post) {
        echo '<div class="posts">';
        $thumbnail = file_get_contents('http://localhost/noticias/wp-json/wp/v2/media/' . $post->featured_media);
        $image = json_decode($thumbnail);
        echo '<img src="' . $image->media_details->sizes->codilight_lite_block_2_medium->source_url . '"/>';
        echo '<h2><a href="' . $post->link . '">' . $post->title->rendered . '</a></h2>';
        echo '<p>' . $post->excerpt->rendered . '</p>';
        echo '<p>' . $post->date . '</p>';

        echo '</div>';
    }
    ?>
    
07.11.2017 / 19:22