14

I can pass integer values to WP REST API. But, cannot pass non-numeric characters. It gives error.

This is what I used...

add_action( 'rest_api_init', function () {
    register_rest_route( 'crowdapi/v1', '/register/(?P<id>\d+)/(?P<username>\d+)', array(
        'methods' => 'POST',
        'callback' => 'userCheck',
    ) );
} );

Any idea how to pass strings as well.. ?

Tharindu Thisarasinghe
  • 3,846
  • 8
  • 39
  • 70

4 Answers4

28

I found it myself...

use [a-zA-Z0-9-] instead of \d for strings

add_action( 'rest_api_init', function () {
    register_rest_route( 'crowdapi/v1', '/register/(?P<id>\d+)/(?P<number>[a-zA-Z0-9-]+)', array(
        'methods' => 'POST',
        'callback' => 'userCheck',
    ) );
} );
Tharindu Thisarasinghe
  • 3,846
  • 8
  • 39
  • 70
6

This worked for me: /(?P<slug>\w+)

user3878652
  • 61
  • 1
  • 2
3

Try below code for define endpoint as well..

add_action( 'rest_api_init', function () {
    register_rest_route( 'crowdapi/v1', '/register/(?P<id>\d)/(?P<username>\d)', array(
        'methods' => 'POST',
        'callback' => 'userCheck',
    ) );
} );
Ashish Patel
  • 3,551
  • 1
  • 15
  • 31
  • I've used `(?P.+)` as well as `(?P[^/]+)` for string params. It really depends on what you need to get back as well as put-in. – MrMesees Feb 23 '18 at 13:44
0

you need to try this, it will work

add_action( 'rest_api_init', function () {
    register_rest_route( 'crowdapi/v1', '/register/(?P<id>\d+)/(?P<username>\w+)', array(
        'methods' => 'POST',
        'callback' => 'userCheck',
    ) );
} );
Nikul Panchal
  • 1,542
  • 3
  • 35
  • 58