带有 URL 参数的 WordPress REST API 自定义端点 [英] WordPress REST API Custom Endpoint with URL Parameter
问题描述
我正在尝试为 WordPress REST API 创建自定义端点并通过 URL 传递参数.
I am trying to create a custom endpoint for the WordPress REST API and pass parameters through the URL.
当前端点为:
/wp-json/v1/products/81838240219
我想要实现的是一个看起来像这样的端点,并且能够在回调中检索标识符参数.
What I am trying to achieve is an endpoint that looks like this and being able to retrieve the identifier parameter in the callback.
/wp-json/v1/products?identifier=81838240219
// Custom api endpoint test
function my_awesome_func( $data ) {
$identifier = get_query_var( 'identifier' );
return $identifier;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'api/v1', '/products=(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
推荐答案
首先需要将命名空间传入register_rest_route
像这样
add_action( 'rest_api_init', function () {
register_rest_route( 'namespace/v1', '/product/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
你的名字空间 namespace/v1
和你的路线是 /product/{id}
像这样/namespace/v1/product/81838240219
Your name space namespace/v1
and your route is /product/{id}
like this
/namespace/v1/product/81838240219
现在你可以像这样在你的函数中使用路由
and now you can use the route inside your function like this
function my_awesome_func( $data ) {
$product_ID = $data['id'];
}
如果您需要为 ex 添加选项./namespace/v1/product/81838240219?name=Rob
If you need to add options for ex. /namespace/v1/product/81838240219?name=Rob
并像这样在函数内部使用它
and use it inside the function like this
function my_awesome_func( $data ) {
$product_ID = $data['id'];
$name = $data->get_param( 'name' );
}
过程非常简单,但需要您阅读此文档
The process is very simple but requires you to read this documentation
这篇关于带有 URL 参数的 WordPress REST API 自定义端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!