WP REST API – GET with 2 or more variables

I was searching the WP REST Documentation and have been googling around but I haven’t seen some examples using GET method with multiple variable so I just played around with the code and URL and way able to get integer values when using this code in your custom plugin or functions.php:

add_action( 'rest_api_init', function () {
register_rest_route(
'testapi/v1', '/getvars/(?P<var1>\d+)/(?P<var2>\d+)', array(
'methods' => 'GET',
'callback' => 'wp_restapi_getvars',
)
);
}
);
function wp_restapi_getvars( $data ) {
echo 'This is var1:' . $data['var1'] . '<br>';
echo 'This is var2:' . $data['var2'] . '<br>';
}

And when you try this example URL :

http://example.com/wp-json/testapi/v1/getvars/123/456

This will give you an output of:

This is var1:123

This is var2:456

I think I need to dig and explore more to expand its usage especially on other data types other than integers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.