WP Rest API Get Featured Image

jeastham1993 picture jeastham1993 · Sep 19, 2015 · Viewed 8.6k times · Source

I am building a relatively simply blog page that uses the WP Rest Api and AngularJs to show the data on the front-end.

On my home page I want to return the title, followed by the featured image, followed by the excerpt. I have pulled the title and excerpt in fine it seems that in the JSON the featured image is a media Id. What is the best way to pull this data in on the fly?

I have seen various things around the internet that use PHP functions but I think the best way to do it is within a angular controller, just looking for some advice on exactly what the controller would be

List View HTML

<ng-include src=" dir + '/form.html?v=2' "></ng-include>
<div class="row">
    <div class="col-sm-8 col-lg-10 col-lg-push-1 post">         
        <div class="row-fluid">
            <div class="col-sm-12">
                <article ng-repeat="post in posts" class="projects">
                    <a class="title" href="#/post/{{post.slug}}"><h2>{{post.title.rendered}}</h2></a>
                    <p ng-bind-html="post.excerpt.rendered | to_trusted"></p>
                </article>
            </div>
        </div>
    </div>
</div>  

Controller

.controller('listPage',['$scope','Posts', function($scope,Posts){

    $scope.refreshPosts = function(){
        Posts.query(function(res){
            $scope.posts = res;
        });
    };
    $scope.refreshPosts();

    // CLEARFORMFUNCTION
    $scope.clear = function(){
        $scope.$root.openPost = false;
        jQuery('#save').modal('hide');
    };


    // SAVEMODALOPEN/COSE
    $scope.openSaveModal = function(){
        jQuery('#save').modal('show');
    }

    $scope.closeSaveModal = function(){
        jQuery('#save').modal('hide');
    }

    // DATEFUNCTION
    $scope.datify = function(date){
        $scope.date = newDate(date);
        return $scope.date.getDate()+'/'+$scope.date.getMonth()+'/'+$scope.date.getYear();
    };
}])

Answer

StephanieQ picture StephanieQ · Dec 19, 2016

You could also modify the JSON response with PHP. This returns just what I need and is very fast (Using _embed is very slow in my experience)

I have the following code in a plugin (used for adding custom post types), but I imagine you could put it in your theme's function.php file.

php

add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
function add_thumbnail_to_JSON() {
//Add featured image
register_rest_field( 'post',
    'featured_image_src', //NAME OF THE NEW FIELD TO BE ADDED - you can call this anything
    array(
        'get_callback'    => 'get_image_src',
        'update_callback' => null,
        'schema'          => null,
         )
    );
}

function get_image_src( $object, $field_name, $request ) {
    $size = 'thumbnail'; // Change this to the size you want | 'medium' / 'large'
    $feat_img_array = wp_get_attachment_image_src($object['featured_media'], $size, true);
    return $feat_img_array[0];
}

Now in your JSON response you should see a new field called "featured_image_src": containing a url to the thumbnail.

Read more about modifying responses here:
http://v2.wp-api.org/extending/modifying/

And here's more information on the wp_get_attachment_image_src() function https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/

**Note: Don't forget <?php ?> tags if this is a new php file!