我正在尝试通过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() { ... }
代码是相同的。
知道为什么它不起作用吗?
答案 0 :(得分:4)
如果您查看文档(Adding Custom Endpoints | WordPress REST API),则会注意到$data
实际上是一个数组,因此您的代码无法执行您期望的操作,因为您正在将数组传递给get_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'
]
));
});
答案 1 :(得分:3)
尝试这种方式
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 );
}