Search code examples
jsonwordpresswordpress-rest-api

How to use wp:featuredmedia in WP REST API response?


I am trying to get blog posts from another WordPress site, as of now I am successfully fetching the posts, I am using the following snippet:

$response = wp_remote_get( add_query_arg( array(
    'per_page' => 1,
     'categories' => 38
     ), 'https://www.remotesite.com/wp-json/wp/v2/posts?_embed' ) 
);
if( !is_wp_error( $response ) && $response['response']['code'] == 200 ) {

   $remote_posts = json_decode( $response['body'] ); 
    foreach( $remote_posts as $remote_post ) {
    echo '<h2>'. $remote_post->title->rendered . '</h2>
           <p>' . $remote_post->excerpt->rendered . '</p>';     

   }
 }

with the above code, I can fetch all the required details, title, excerpt, and Featured Image. But I am having a very hard time to find how to get the Featured Image url from the above response. Can anyone tell me how to use the wp:featuredmedia from the response. I have seen somewhere the below code to get the featured image URL, but this won't helped me:

echo [your-data]._embedded['wp:featuredmedia']['0'].source_url

Solution

  • Based on your code, the featured image URL can be retrieved like this:

    $remote_post->_embedded->{'wp:featuredmedia'}[0]->source_url
    

    That is, however, the full-sized version of the featured image file.

    To get the URL of a specific thumbnail size, you can access if from:

    $remote_post->_embedded->{'wp:featuredmedia'}[0]->media_details->sizes
    

    .. which is an array of object data (unless of course you use true in the second parameter of the json_decode() function).

    By default, the available thumbnail sizes are: thumbnail, medium, and medium_large. Here's an example for the medium size:

    $remote_post->_embedded->{'wp:featuredmedia'}[0]->media_details->sizes->medium->source_url
    

    So try this foreach:

    foreach( $remote_posts as $remote_post ) {
        $thumb_full_url = '';
        $thumb_url = '';
    
        if ( ! empty( $remote_post->featured_media ) && isset( $remote_post->_embedded ) ) {
            $thumb_full_url = $remote_post->_embedded->{'wp:featuredmedia'}[0]->source_url;
            $thumb_url = $remote_post->_embedded->{'wp:featuredmedia'}[0]->media_details->sizes->medium->source_url;
        }
    
        echo '<h2>'. $remote_post->title->rendered . '</h2>' .
            '<p>' . $remote_post->excerpt->rendered . '</p>' .
            '<p>' .
                'Medium-sized thumbnail: ' . $thumb_url . '<br>' .
                'Full-sized / source: ' . $thumb_full_url .
            '</p>';
    }