admin管理员组

文章数量:1426950

I noticed that often in register_rest_routes, are used regexp like ?P<lang>, ?P<category_id>\d+ and so on, but I guess it's not standard regexp syntax. What exactly does it do?

I noticed that often in register_rest_routes, are used regexp like ?P<lang>, ?P<category_id>\d+ and so on, but I guess it's not standard regexp syntax. What exactly does it do?

Share Improve this question asked May 24, 2019 at 14:10 Luca ReghellinLuca Reghellin 1,6422 gold badges21 silver badges45 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

It's called a path variable:

Path variables enable us to add dynamic routes.

See below example taken from the REST API handbook:

// Here we are registering our route for single products. The (?P<id>[\d]+) is
// our path variable for the ID, which, in this example, can only be some form
// of positive number.
register_rest_route( 'my-shop/v1', '/products/(?P<id>[\d]+)', array(
    ...
    'callback' => 'prefix_get_product',
) );

The important part to note is that in the second route we register (the one above), we add on a path variable /(?P<id>[\d]+) to our resource path /products. The path variable is a regular expression. In this case it uses [\d]+ to signify that should be any numerical character at least once. If you are using numeric IDs for your resources, then this is a great example of how to use a path variable. When using path variables, we now have to be careful around what can be matched as it is user input.

And the format is: ?P<{name}>{regex pattern}.

And based on the above example, one could go to http://example/wp-json/my-shop/v1/products/123 to retrieve a single resource.

PS: I edited mainly to add the second paragraph above.

本文标签: