Reputation: 4291
What's the easiest way to fetch the number of comments 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.
Upvotes: 3
Views: 1920
Reputation: 815
If 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', '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',
],
] );
});
If you don't have access to the site you are requesting, you can have the comments 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 );
});
Upvotes: 7
Reputation: 51
Not so much a JavaScript related question but here's an answer anyway.
The easiest way to get the number of comments for any post aside from adding a custom endpoint to the REST API is to use the comments endpoint (https://site/wp-json/wp/v2/comments?post=1234&per_page=1) and use the response's X-WP-Total
header.
Upvotes: 3