2

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();
    };
}])
plantpowerjames
  • 375
  • 2
  • 10
  • 22
  • Here is a link that might be useful: https://1fix.io/blog/2015/06/26/adding-fields-wp-rest-api/ – Cyclonecode Sep 19 '15 at 09:51
  • Great link, works fine for adding a custom field to return the thumbnail URL. I notice it uses a get_post_thumbnail_id function, is there a similar call to return the post_large – plantpowerjames Sep 19 '15 at 11:09

3 Answers3

6

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!

StephanieQ
  • 872
  • 1
  • 13
  • 21
3

Turns out, in my case, there is a new plugin available that solves this without having to make a secondary request. See my recent Q:

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

Community
  • 1
  • 1
redshift
  • 4,815
  • 13
  • 75
  • 138
3

If you send the ?_embed param to the query, it will return more information in the response, like images, categories, and author data.

const result = await axios.get(`/wp-json/wp/v2/my-post-type?_embed`);

// Featured Image
result.data._embedded['wp:featuredmedia'][0].source_url;

// Thumbnail
result.data._embedded['wp:featuredmedia'][0]['media_details']['sizes']['medium']['source_url']

ecairol
  • 6,233
  • 1
  • 27
  • 26