cda*_*win 2 javascript wordpress-rest-api
获取帖子的评论数量和点赞数量的最简单方法是什么?
获取帖子时我没有看到任何有用的字段(带有类似https://site/wp-json/wp/v2/posts?after=2018-07-21T15:05:44.000Z 的请求)
我目前正在使用 javascript 通过axios发出直接请求。
如果您对所请求的站点的代码具有编辑权限,则可以将该字段添加到 JSON API 提供的响应中。
像这样的东西:
add_action( 'rest_api_init', function() {
\register_rest_field( 'post', 'comment_count', [
'get_callback' => function ( $post ) {
return (int) wp_count_comments( $post['id'] )->approved;
},
'schema' => [
'description' => 'List number of comments attached to this post.',
'type' => 'integer',
],
] );
});
Run Code Online (Sandbox Code Playgroud)
如果您无权访问所请求的网站,则可以通过?_embed=true在 URL 末尾发送来将评论添加到响应中,然后简单地计算回复数。
像这样的东西:
const {data} = await Axios.get( 'https://site/wp-json/wp/v2/posts?after=2018-07-21T15:05:44.000Z&_embed=true' );
data.map( post => {
console.log( post._embedded.replies.length );
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1791 次 |
| 最近记录: |