Display featured posts and image using Wordpress REST API

Asked

Viewed 755 times

1

I want to display the last two Wordpress posts using API Rest, after many searches and test manage to do this gambit there, but after I put this foreach inside the other one got a little slow, it would be nice if you could show the images of each post without needing a new foreach.

Does it have how to 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>';
    }
    ?>

1 answer

0

You can do it like 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>';
    }
    ?>
  • you know how to use Curl instead of file_get_contents? because by default and security issue this file_get_contents function is disabled on hosting servers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.