2

I am trying to get the featured image of a post using the WordPress REST API. I am adding the extention of ?embed to the end if the REST API url and I am seeing the featured image data under ['wp:featuredmedia'], but I can't seem to display that data.

I am using Vue to display data from the REST API and so what I am doing currently to try and get the featured image source is: post._embedded['wp:featuredmedia'][0].source_url

But by doing that it can't find the source url of the featured image and I am not sure what is wrong with my path for it to not find the source url data?

2
  • It sounds like you're on the right path. However, without a specific code snippet to look at what you're doing, it's hard to say what the problem is. You could improve this question and get better answers if you post what you're using now to get the image and (attempt to) display it.
    – butlerblog
    Commented Nov 30, 2018 at 20:08
  • @butlerblog with Vue I am using {{ post._embedded['wp:featuredmedia'][0].source_url }} inside a div tag, with the normal Wordpress REST API Commented Nov 30, 2018 at 20:14

2 Answers 2

0

I used Better REST API Featured Image plugin. that adds the featured image URL to the original API response.

0

If you do not want to add extra plug-in for that, you could add inside functions.php file the code below:

add_action('rest_api_init', 'register_rest_images' );function register_rest_images(){
    register_rest_field( array('post'),
        'featured_image', //**this is the name appears on json response**
        array(
            'get_callback'    => 'get_rest_featured_image',
            'update_callback' => null,
            'schema'          => null,
        )
    );
}function get_rest_featured_image( $object, $field_name, $request ) {
    if( $object['featured_media'] ){
        $img = wp_get_attachment_image_src( $object['featured_media'], 'app-thumb' );
        return $img[0];
    }
    return false;
}

Thus, in PHP after parsing the response you could display the image like this:

$view_posts = json_decode($curl_res);
foreach ($view_posts as $post_data) {
    $post_info[$count]['image']         = (string)$post_data->featured_image;
    //your code
} //end foreach loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.