TL; DR :如何选择WP REST API自定义端点响应的每一位信息?
LONG VERSION
如果我想使用WP REST API构建自定义端点 - 从不同的帖子类型发送特定的帖子数据 - 按照Handbook中的示例,我得到了这个:
function custom_endpoint ( $data ) {
$posts = get_posts( array(
'numberposts' => -1,
'post_type' => array('event', 'post'),
) );
if ( empty( $posts ) ) {
return null;
}
return $posts;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v1', '/custom-endpoint/', array(
'methods' => 'GET',
'callback' => 'custom_endpoint',
) );
} );
但是get_post()函数不会返回一些非常有用的数据,如果你想在你的页面中显示帖子(类别id,特色图像,用于intance)。那么如何构建一个返回的自定义端点:
答案 0 :(得分:1)
基于@fsn的答案,我得到了以下想法:使用其他Wordpress函数获取get_posts()返回并添加新比例的对象。
function custom_endpoint ( $data ) {
$posts = get_posts( array(
'numberposts' => -1,
//Here we can get more than one post type. Useful to a home page.
'post_type' => array('event', 'post'),
) );
if ( empty( $posts ) ) {
return null;
}
$args = array();
foreach ( $posts as $post ) {
//Get informations that is not avaible in get_post() function and store it in variables.
$category = get_the_category( $post->ID );
$img_thumb = get_the_post_thumbnail_url( $post->ID, 'thumbnail' ); // Thumbnail (default 150px x 150px max)
$img_medium = get_the_post_thumbnail_url( $post->ID, 'medium' ); // Medium resolution (default 300px x 300px max)
$img_large = get_the_post_thumbnail_url( $post->ID, 'large' ); // Large resolution (default 640px x 640px max)
$img_full = get_the_post_thumbnail_url( $post->ID, 'full' ); // Full resolution (original size uploaded)
//Adds the informations to the post object.
$post->category = $category;
$post->img_tumb = $img_thumb;
$post->img_medium = $img_medium;
$post->img_large = $img_large;
$post->img_full = $img_full;
array_push($args, $post);
}
return $args;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v1', '/custom-endpoint/', array(
'methods' => 'GET',
'callback' => 'custom_endpoint',
) );
});
一切正常!
谢谢@fsn的贡献。
答案 1 :(得分:0)
作为访问所有数据的WP Codex states:
访问所有帖子数据一些与帖子相关的数据不可用到get_posts。
你可以通过以下方式获得它们:
$posts = get_posts( array(
'numberposts' => -1,
'post_type' => array('event', 'post'),
) );
$response = [];
foreach ( $posts as $post ) {
$response[] = [
'content' => $post->CONTENT.
'title' => $post->TITLE,
.....
]
}
return $response; (in a WP way of constructing json responses)