admin管理员组文章数量:1403203
What's the easiest way to fetch the number of ments and the number of likes a post has?
I don't see any usefull field when fetching a post (with a request like https://site/wp-json/wp/v2/posts?after=2018-07-21T15:05:44.000Z)
I'm currently using javascript issuing direct requests with axios.
What's the easiest way to fetch the number of ments and the number of likes a post has?
I don't see any usefull field when fetching a post (with a request like https://site/wp-json/wp/v2/posts?after=2018-07-21T15:05:44.000Z)
I'm currently using javascript issuing direct requests with axios.
Share Improve this question asked Aug 18, 2018 at 15:35 cdarwincdarwin 4,30110 gold badges47 silver badges70 bronze badges2 Answers
Reset to default 7If you have edit access to the code of the site your are requesting, you could add the field to the responses provided by the JSON API.
Something like this:
add_action( 'rest_api_init', function() {
\register_rest_field( 'post', 'ment_count', [
'get_callback' => function ( $post ) {
return (int) wp_count_ments( $post['id'] )->approved;
},
'schema' => [
'description' => 'List number of ments attached to this post.',
'type' => 'integer',
],
] );
});
If you don't have access to the site you are requesting, you can have the ments added to the response by send ?_embed=true
at the end of the URL and simply count the replies.
Something like this:
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 );
});
Not so much a JavaScript related question but here's an answer anyway.
The easiest way to get the number of ments for any post aside from adding a custom endpoint to the REST API is to use the ments endpoint (https://site/wp-json/wp/v2/ments?post=1234&per_page=1) and use the response's X-WP-Total
header.
本文标签: javascriptWordPress REST API comment and like countStack Overflow
版权声明:本文标题:javascript - WordPress REST API: comment and like count - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744409104a2604860.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论