[英]Custom post type REST API custom endpoint for single post by ID
我创建了一个 WordPress 自定义帖子类型,然后我创建了 REST API 自定义端点来获取所有帖子都很好。 然后我创建了另一个自定义端点来通过 ID 获取单个帖子。 例如 http://localhost:8888/wordpress/wp-json/lc/v1/cars/120
我创建了一些帖子,每次我将路线末尾的 ID 更改为 118 或 116 时,它都会显示最新帖子 ID 120 的相同数据。我需要根据帖子 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.