Tharindu Thisarasinghe
Tharindu Thisarasinghe

Reputation: 3998

Pass String Parameters to WP REST API

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.. ?

Upvotes: 14

Views: 18052

Answers (4)

Nikul Panchal
Nikul Panchal

Reputation: 1673

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',
    ) );
} );

Upvotes: 0

user3878652
user3878652

Reputation: 61

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

Upvotes: 6

Ashish Patel
Ashish Patel

Reputation: 3614

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',
    ) );
} );

Upvotes: 3

Tharindu Thisarasinghe
Tharindu Thisarasinghe

Reputation: 3998

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',
    ) );
} );

Upvotes: 29

Related Questions