我可以根据调用方法定义多个回调方法吗?

时间:2019-04-12 作者:TTT

他是我当前的自定义API:

add_action( \'rest_api_init\', function () {
  register_rest_route(\'my-project/v1/form\', \'/get\', array(
    \'methods\' => WP_REST_Server::READABLE,
    \'callback\' => \'get_form\'
  ));
});


add_action( \'rest_api_init\', function () {
  register_rest_route(\'my-project/v1/form\', \'/post\', array(
    \'methods\' => \'POST\',
    \'callback\' => \'post_form\'
  ));
});
这里有一些我想写的东西,但我不确定是否可能。我可以肯定的是,这个语法

add_action( \'rest_api_init\', function () {
  register_rest_route(\'my-project/v1/\', \'/form\',
array(
    \'methods\' => \'GET\',
    \'callback\' => \'GET_form\',
  ), array(
    \'methods\' => \'POST\',
    \'callback\' => \'post_form\',
  ), );
});

1 个回复
SO网友:nmr

检查您的代码是否如下所示,因为在问题中,您将每个方法作为单独的函数参数传递(我之前忽略了它)

add_action( \'rest_api_init\', function () {

    register_rest_route(\'my-project/v1/\', \'/form\', 
        array(
            array(\'methods\' => \'GET\',
                 \'callback\' => \'GET_form\',
            ), 
            array(\'methods\' => \'POST\',
                 \'callback\' => \'post_form\'
            )
        ) 
    );
});
正如你所读到的documentation:

参数#

$args - (阵列)(可选)

端点的选项数组,or an array of arrays for multiple methods.
默认值:array()