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

前端 未结 4 1216
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 03:44

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 feat

4条回答
  •  时光取名叫无心
    2021-01-18 04:27

    A better way would be to integrate the URL of the featured image into the json response so that you get it all in a single request. You can add the following code (inside your-theme/functions.php) to achieve this:

    //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' );
    

    Then in your view, you can use {{ post.featured_image }}

    Note: To get the same image in different sizes, use above wp_get_attachment_image_src function that accepts any valid image size, or an array of width and height values in pixels as its second parameter.

提交回复
热议问题