自定义 post 类型 REST API 单个 post 的自定义端点(按 ID)

Custom post type REST API custom endpoint for single post by ID

我已经创建了一个 WordPress 自定义 post 类型,然后我创建了 REST API 自定义端点以获取所有 posts 工作正常。然后我创建了另一个自定义端点以通过 ID 获取单个 post。例如 http://localhost:8888/wordpress/wp-json/lc/v1/cars/120

我创建了几个 posts,每次我将路线末端的 ID 更改为 118 或 116 时,它会显示最新的 post-ID 120 的相同数据。我需要根据 post ID 显示相关数据,我将不胜感激。谢谢

public function rest_posts_endpoints(){

register_rest_route( 
        'lc/v1',
        '/cars/(?P<id>\d+)',
        [
            'method' => 'GET', 
            'callback' => [$this, 'rest_endpoint_handler_single'], 
        ]
    );
}

public function rest_endpoint_handler_single($id) { 

    $args = [
         'post_type' => 'cars',
         'id' => $id['id'],
    ];

    $post = get_posts($args);

        $data['id'] = $post[0]->ID;
        $data['slug'] = $post[0]->post_name;
        $data['title'] = $post[0]->post_title;
        $data['content'] = $post[0]->post_content;
        $data['excerpt'] = $post[0]->post_excerpt;

    return $data;
}

请使用 WP_REST_Request $request 获取传递的参数。

public function rest_endpoint_handler_single(WP_REST_Request $request) { 

    $params = $request->get_query_params();

    $args = [
         'post_type' => 'cars',
         'numberposts' => 1,
         'include' => array($params['id']),
    ];

    $post = get_posts($args);

        $data['id'] = $post[0]->ID;
        $data['slug'] = $post[0]->post_name;
        $data['title'] = $post[0]->post_title;
        $data['content'] = $post[0]->post_content;
        $data['excerpt'] = $post[0]->post_excerpt;

    return $data;
}