自定义 Wordpress REST API JSON

Custom Wordpress REST API JSON

如何修改新的 wp-json REST API post 数据?

我当前的json结构(/wp-json/myspace/v1/get-by-tag/test0/1):

{
   "items":{
      "posts":[
         {
            "title":"Stay up-to-date with the one latest tech [cloned]"
         }
      ]
   }
}

为了举例,我删减了数据...

PHP REST API 初始化和 Post 查询:

add_action( 'rest_api_init', function () {
    register_rest_route( 'myspace/v1/', 'get-by-tag/(?P<slug>[a-z0-9]+(?:-[a-z0-9]+)*)/(?P<page>[1-9]{1,2})', array(
        'methods' => WP_REST_Server::READABLE,
        'callback' => 'myspace_get_posts_by_tag',
        'args' => array(
            'slug' => array(
                'required' => true
            ),
            'page' => array(
                'required' => true
            ),                  
        )
    ));
});

function myspace_get_posts_by_tag(WP_REST_Request $request) {

    $slug = $request['slug'];
    $page = $request['page'];

    $term = get_term_by('slug', $slug, 'post_tag');
    $posts_per_page = 1;

    $args = array(
        'tag__in'           => $term->term_id,
        'posts_per_page'    => $posts_per_page,
        'paged'             => $page,
        'orderby'           => 'date',
        'order'             => 'desc',
    );

    $query = new WP_Query( $args ); 

    $max_pages = $query->max_num_pages;
    $total = $query->found_posts;

    $posts = $query->posts;
    $controller = new WP_REST_Posts_Controller('post');

    foreach ( $posts as $post ) {

        //echo $max_pages;
        //echo $page;
        
         $data["items"]["posts"][] = array(
             //extra post content goes here
             "title" => $post->post_title
         );     
        
    }
     
    $response = new WP_REST_Response($data, 200);
    $response->header( 'X-WP-Total', $total ); 
    $response->header( 'X-WP-TotalPages', $max_pages );
    return $response;
}

$max_pages = the total amount of pages
$page = current page number

如何将这些值推送到我的数组以实现以下 JSON 结构:

{
   "items":{
      "currentPage":1,
      "pageCount":5,
      "posts":[
               {
                  "title":"Stay up-to-date with the one latest"
               },
               {
                  "title":"Stay up-to-date with the one latest"
               }
      ]
   }
}
function my_posts() {
     $posts_list = get_posts( array( 'type' => 'post' ) );
     $post_data = array( "posts" => array());
 
     foreach( $posts_list as $posts) {
         $post_id = $posts->ID;
         $post_title = $posts->post_title;
         $post_data["posts"][] = array(
             "id" => $post_id,
             "title" => $post_title
         );
     }
 
     wp_reset_postdata();
     return rest_ensure_response( $post_data );
 }