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();
};
}])
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
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()
functionhttps://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/
**Note: Don’t forget
<?php ?>
tags if this is a new php file!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?
If you send the
?_embed
param to the query, it will return more information in the response, like images, categories, and author data.