[태그:] REST API

  • WordPress REST API posts 목록에 댓글 카운트 추가하기

    WordPress의 기본 REST API중 posts에는 따로 댓글의 카운트를 따로 뽑아주는 기능이 없어 검색해보니..
    역시나 누군가 만들어둔게 있어 퍼옵니다.

    WordPress /wp-content/themes/{사용 테마} 폴더의 functions.php에 추가후 확인

    // https://stackoverflow.com/a/60048982
    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',
            ],
        ] );
    });