无法使用 get_post() 通过 REST API 检索自定义 post 类型数据

Can't retrieve custom post type data through REST API using get_post()

我正在尝试从 post 类型的自定义 post 到 REST API 中获取数据。使用 get_posts() 它工作正常:

function single_project($data) {
  $args = array(
    'post_type' => 'project',
    'posts_per_page'=> 1,
    'p' => $data
  );  
  return get_posts($args);
}

add_action('rest_api_init', function () {
  register_rest_route( 'project/v1', 'post/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'single_project',
    'args' => [
      'id'
    ]
  ));
});

但在我的前端我得到一个数组,我必须从该数组的第一个也是唯一一个项目中获取数据,这并不好。

get_post() 听起来像是解决方案,但由于某些原因它不起作用:ID 没有通过 REST API 传递,我不明白为什么。

function single_project($data) {
  return get_post($data);
}

add_action() { ... } 代码相同。

知道为什么它不起作用吗?

试试这个方法

add_action( 'rest_api_init', 'my_register_route');
function my_register_route() {

      register_rest_route( 'my-route', 'my-posts/(?P<id>\d+)', array(
            'methods' => 'GET',
            'callback' => 'my_posts',
            'args' => array(
                    'id' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return is_numeric( $param );
                        }
                    ),
                ),
            'permission_callback' => function() {
                return current_user_can( 'edit_others_posts' );
                }, 
        );
}

function my_posts( $data ) {

    // default the author list to all
    $post_author = 'all';

    // if ID is set
    if( isset( $data[ 'id' ] ) ) {
          $post_author = $data[ 'id' ];
    }

    // get the posts
    $posts_list = get_posts( array( 'type' => 'post', 'author' => $post_author ) );
    $post_data = array();

    foreach( $posts_list as $posts) {
        $post_id = $posts->ID;
        $post_author = $posts->post_author;
        $post_title = $posts->post_title;
        $post_content = $posts->post_content;

        $post_data[ $post_id ][ 'author' ] = $post_author;
        $post_data[ $post_id ][ 'title' ] = $post_title;
        $post_data[ $post_id ][ 'content' ] = $post_content;
    }

    wp_reset_postdata();

    return rest_ensure_response( $post_data );
}

如果您查看文档(Adding Custom Endpoints | WordPress REST API) you'll notice that $data is actually an array and so your code fails to do what you expect it to do because you're passing an array to the get_post() 需要整数(post ID)或 WP_Post 对象的函数。

所以:

function single_project($data) {
  $post_ID = $data['id'];
  return get_post($post_ID);
}

add_action('rest_api_init', function () {
  register_rest_route( 'project/v1', 'post/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'single_project',
    'args' => [
      'id'
    ]
  ));
});