WordPress Rest API custom endpoint optional param

You should put the named parameters of the route regex into an optional capturing group:

register_rest_route( 'api', '/animals(?:/(?P<id>\d+))?', [
   'methods' => WP_REST_Server::READABLE,
   'callback' => 'get_animals',
   'args' => [
        'id'
    ],
] );

The second parameter is simply a regex, thus you can use normal regex logic to make it more complex

Leave a Comment