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

I access Wordpress data through the HTTP REST API (this wordpress plugin: http://v2.wp-api.org/ ). I know how to capture my message header, but how can I display the image associated with this message using this plugin? My test shows the record name and image id, but I'm not sure how to display the actual image. Test example .

Here is 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>
+4
source share
4 answers

, _embed . :

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

JSON _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;
    });
});
+4

URL- json, . ( /functions.php), :

//Get image URL
function get_thumbnail_url($post){
    if(has_post_thumbnail($post['id'])){
        $imgArray = wp_get_attachment_image_src( get_post_thumbnail_id( $post['id'] ), 'full' ); // replace 'full' with 'thumbnail' to get a thumbnail
        $imgURL = $imgArray[0];
        return $imgURL;
    } else {
        return false;
    }
}
//integrate with WP-REST-API
function insert_thumbnail_url() {
     register_rest_field( 'post',
                          'featured_image',  //key-name in json response
                           array(
                             'get_callback'    => 'get_thumbnail_url',
                             'update_callback' => null,
                             'schema'          => null,
                             )
                         );
     }
//register action
add_action( 'rest_api_init', 'insert_thumbnail_url' );

, , {{ post.featured_image }}

: , wp_get_attachment_image_src , .

+4

<p>{{ post.featured_image }}</p> <img ng-src="{{post.better_featured_image.source_url}}" />

0

Source: https://habr.com/ru/post/1613029/


All Articles