我是Wordpress和REST-API的新手,我已经能够使GET功能正常工作,但我无法将参数传递给post函数。
下面我粘贴了我的代码。输入http://localhost/wp-json/localhost/v1/activeitem时会生成有效ID,但如果我提供http://localhost/wp-json/localhost/v1/activeitem/123,我会收到{"代码":" rest_no_route","消息&#34 ;:"未找到与网址和请求方法匹配的路由","数据":{" status":404}}。
当在Wordpress的REST API控制台中运行/ localhost / v1 / activeitem?45时,我得到了#34;完成"。所以在这一点上我想知道我做错了什么。
想法是xxx / activeitem调用会给出活动ID,而xxx / activeitem [参数]会将活动项更新为提供的id。
function LocalHost_GetActiveItem() {
global $wpdb;
$querystr = "select option_value as pid from wp_options where option_name = 'acelive_active';";
$activeitem = $wpdb->get_results($querystr);
return $activeitem[0];
}
function LocalHost_SetActiveItem($id) {
//return $id;
return "done";
}
add_action( 'rest_api_init', function () {
register_rest_route( 'localhost/v1', '/activeitem/', array(
array(
'methods' => 'GET',
'callback' => 'LocalHost_GetActiveItem',
),
array(
'methods' => 'POST',
'callback' => 'LocalHost_SetActiveItem',
'args' => array('id' => 234)
),
) );
} );
add_action( 'rest_api_init', function () {
register_rest_route( 'localhost/v1', '/lastupdate/', array(
'methods' => 'GET',
'callback' => 'LocalHost_LastUpdate',
) );
} );
答案 0 :(得分:0)
确保您的正则表达式表达式正确。对于id,您可以在register_rest_route()的$ route参数中使用activeitem/(?P<id>[\d]+)
,如果要更新id,请确保
将register_rest_route()的$ override参数设置为true
register_rest_route( 'localhost/v1', '/activeitem/(?P<id>[\d]+)', array(
'methods' => 'POST',
'callback' => 'LocalHost_SetActiveItem',
'args' => array('id' => 234)
), true );
在提供xxx / activeitem / 123时出现404错误的原因是未捕获123并将其作为ID传递到您的url,因为路由未提供正确的正则表达式。