![](/img/trans.png)
[英]WP Rest API custom endpoint returning false on GET and POST
[英]How WP REST API custom endpoint could return custom post data?
TL; DR :如何选择WP REST API自定义端点的响应的所有信息?
长版
如果我想使用WP REST API构建自定义端点-从不同的帖子类型发送特定的帖子数据-按照手册中的示例进行操作,我得到了:
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,特色图片,例如)。 因此,如何构建一个返回以下内容的自定义端点:
基于@fsn答案,我有以下想法:拿取get_posts()返回的对象,并使用其他Wordpress函数向其添加新的比例。
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的贡献。
WP Codex声明要访问所有数据:
访问所有帖子数据某些与帖子相关的数据不可用于 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.