Search code examples
wordpresswordpress-rest-api

Can't retrieve custom post type data through REST API using get_post()


I'm trying to get data from a custom post type single post through REST API. With get_posts() it works fine:

function single_project($data) {
  $args = array(
    'post_type' => 'project',
    'posts_per_page'=> 1,
    'p' => $data
  );  
  return get_posts($args);
}

add_action('rest_api_init', function () {
  register_rest_route( 'project/v1', 'post/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'single_project',
    'args' => [
      'id'
    ]
  ));
});

But in my front-end I get an array and I have to get the data from the first and only item of that array, which is not nice.

get_post() sounds like the solution but for some reason it doesn't work: the ID doesn't get passed through REST API and I can't see why.

function single_project($data) {
  return get_post($data);
}

The add_action() { ... } code is identical.

Any idea why it doesn't work?


Solution

  • If you check the documentation (Adding Custom Endpoints | WordPress REST API) you'll notice that $data is actually an array and so your code fails to do what you expect it to do because you're passing an array to the get_post() function which expects either an integer (the post ID) or a WP_Post object instead.

    So:

    function single_project($data) {
      $post_ID = $data['id'];
      return get_post($post_ID);
    }
    
    add_action('rest_api_init', function () {
      register_rest_route( 'project/v1', 'post/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'single_project',
        'args' => [
          'id'
        ]
      ));
    });