jea*_*993 2 rest wordpress angularjs wp-api
我正在构建一个相对简单的博客页面,它使用 WP Rest Api 和 AngularJs 在前端显示数据。
在我的主页上,我想返回标题,然后是特色图片,然后是摘录。我已经很好地提取了标题和摘录,似乎在 JSON 中,特色图像是媒体 ID。动态提取这些数据的最佳方法是什么?
我在互联网上看到了各种使用 PHP 函数的东西,但我认为最好的方法是在 angular 控制器中,只是寻找一些关于控制器究竟是什么的建议
列表视图 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>
Run Code Online (Sandbox Code Playgroud)
控制器
.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();
};
}])
Run Code Online (Sandbox Code Playgroud)
您还可以使用 PHP 修改 JSON 响应。这将返回我需要的并且非常快(根据_embed我的经验使用非常慢)
我在插件中有以下代码(用于添加自定义帖子类型),但我想你可以把它放在你的主题function.php文件中。
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];
}
Run Code Online (Sandbox Code Playgroud)
现在,在您的 JSON 响应中,您应该看到一个名为的新字段,"featured_image_src":其中包含缩略图的 url。
在此处阅读有关修改响应的更多信息:http :
//v2.wp-api.org/extending/modifying/
这里有关于wp_get_attachment_image_src()函数
的更多信息https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/
**注意:<?php ?>如果这是一个新的 php 文件,请不要忘记标签!
| 归档时间: |
|
| 查看次数: |
8741 次 |
| 最近记录: |