无法为post method wordpress REST服务传递参数

问题描述 投票:1回答:1

我是Wordpress和REST-API的新手,我已经能够使GET函数正常工作,但无法将参数传递给post函数。下面,我粘贴了我的代码。输入http://localhost/wp-json/localhost/v1/activeitem时,会生成活动ID,但是如果我提供http://localhost/wp-json/localhost/v1/activeitem/123,则会得到{“ code”:“ rest_no_route”,“ message”:“未找到与URL和请求方法匹配的路由”,“ data”: {“状态”:404}}。在Wordpress的REST API控制台中运行/ localhost / v1 / activeitem?45时,我得到了“完成”。所以在这一点上,我想知道我在做什么错。的想法是xxx / activeitem调用将给出活动ID,而xxx / activeitem [parameter]会将活动项更新为提供的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',
    ) );
} );
php wordpress rest routes wordpress-rest-api
1个回答
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,因为没有为路由提供正确的正则表达式。

© www.soinside.com 2019 - 2024. All rights reserved.