WordPress REST API Endpoints - how can I allow multiple and optional IDs on the same endpoint?

Viewed 379

I am building a REST API custom endpoint and would like to be able to render a view for multiple posts or a singular view of a post if an ID is specified. I would also like to allow for further ? query parameters to be allowed in both cases.

Example requests:

  1. /posts // no query parameters, use defaults
  2. /posts?fields=id,title,thumbnail&thumbnail_size=medium
  3. /posts/123/?fields=id,title,thumbnail&thumbnail_size=large
  4. /posts/123 // nothing specified again!

Here is the code I currently have:

register_rest_route('wp-api', '/posts/(?P<id>[^/]+)?', [
    'methods' => [WP_REST_Server::READABLE, WP_REST_Server::CREATABLE],
    'callback' => function ($request) {
        return MyClass::wp_api_get_posts($request);
    },
]);

This code is working for use-cases 3 and 4 but because of the / in the rest route, use cases 1 and 2 do not work and I simply receive the rest_no_route error (No route was found matching the URL and request method).

I believe the problem to be my regex, but I can't figure out how to fix it.

0 Answers
Related