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 badges
Add a ment  | 

2 Answers 2

Reset to default 7

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', '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