【问题标题】:Custom post type API custom endpoint for single post by ID单个帖子的自定义帖子类型 API 自定义端点(按 ID)
【发布时间】:2020-07-15 14:03:01
【问题描述】:

我创建了一个 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( WP_REST_Request $request ) { 

$params = $request->get_query_params();

$args = [
     'post_type' => 'cars',
     'id' => $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;

}

【问题讨论】:

  • 如果有人也需要帮助,请在下方回答!

标签: wordpress api post routes endpoint


【解决方案1】:
public function rest_endpoint_handler_single( WP_REST_Request $request ) { 

$params = $request->get_params();

 $args = [
   'post_type' => 'cars',
   'id' => $params['id'],
   '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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    相关资源
    最近更新 更多