London Creative
London Creative

Reputation: 45

Custom post type API custom endpoint for single post by ID

I've created a WordPress custom post type, then I've created REST API custom endpoint to GET all the posts works ok. Then I've created another custom endpoint to GET single post by ID. For example http://localhost:8888/wordpress/wp-json/lc/v1/cars/120

I have created a few posts, each time I change the ID at the end of the route to 118 or 116 it shows the same data for the latest post-ID 120. I need the relevant data to show based on the post ID, I would appreciate any kind of help. Thanks

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;

}

Upvotes: 0

Views: 1801

Answers (1)

London Creative
London Creative

Reputation: 45

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;
}

Upvotes: 1

Related Questions