WP Rest API + AngularJS : How to grab Featured Image for display on page?

redshift picture redshift · Oct 24, 2015 · Viewed 10.4k times · Source

I am accessing Wordpress data through an HTTP REST API plugin (this wordpress plugin: http://v2.wp-api.org/). I know how to grab my post title, but how do I display the featured image associated with that post using this plugin? My test shows the post title and the featured image ID, but I am unsure how to display the actual image. Test Example.

Here's my code:

    <div ng-app="myApp">
    <div ng-controller="Ctrl">
        <div ng-repeat="post in posts | limitTo: 1">
            <h2 ng-bind-html="post.title.rendered"></h2>

            <p>{{ post.featured_image }}</p>

        </div>
    </div>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-sanitize.min.js"></script>

<script>

var app = angular.module('myApp', ['ngSanitize']);
    app.controller('Ctrl', function($http, $scope) {
        $http.get("http://ogmda.com/wp/wp-json/wp/v2/posts").success(function(data) {
        $scope.posts = data;
    });
});

</script>

Answer

JeeShen Lee picture JeeShen Lee · Jul 12, 2017

To get featured images response, please add _embed on the query string. example:

http://demo.wp-api.org/wp-json/wp/v2/posts/?_embed

Then, access the featured images in returned JSON response using _embedded['wp:featuredmedia'][0].media_details.sizes.thumbnail.source_url

var app = angular.module('myApp', ['ngSanitize']);
    app.controller('Ctrl', function($http, $scope) {
        $http.get("http://ogmda.com/wp/wp-json/wp/v2/posts?_embed").success(function(data) {
        $scope.posts = data;

        var firstFeaturedImageUrl = $scope.posts[0]._embedded['wp:featuredmedia'][0].media_details.sizes.thumbnail.source_url;
    });
});