为 WordPress REST API 创建自定义端点未注册

bst*_*s21 6 wordpress wordpress-rest-api

我遵循了几个示例,但似乎无法注册自定义端点。我正在创建一个自定义插件并想注册一个自定义端点。这是我的代码:

add_action( 'init', 'setup_init' );


function setup_init() {

   add_action( 'rest_api_init', 'wpc_register_wp_api_endpoints' );

   function wpc_register_wp_api_endpoints() {

    register_rest_route( 'setup', '/client/menu', array(
        'methods' => 'GET',
        'callback' => 'menu_setup',
    ));
}

   function menu_setup($request_data){
       return 'hello world';
   }
}
Run Code Online (Sandbox Code Playgroud)

我访问 mysite.com/setup/client/menu 时出现页面未找到错误。然后我检查 mysite.com/wp-json/wp/v2/,但我没有看到我的路线/终点已注册。我的插件已启用。难道我做错了什么?

小智 0

注册端点时存在一个小错误。更换线路:

register_rest_route( 'setup', '/client/menu'
Run Code Online (Sandbox Code Playgroud)

和:

register_rest_route( 'setup/client', '/menu'
Run Code Online (Sandbox Code Playgroud)

以下是您的代码的完整片段:

add_action( 'init', 'setup_init' );


function setup_init() {

   add_action( 'rest_api_init', 'wpc_register_wp_api_endpoints' );

   function wpc_register_wp_api_endpoints() {

    register_rest_route( 'setup/client', '/menu', array(
        'methods' => 'GET',
        'callback' => 'menu_setup',
    ));
}

   function menu_setup($request_data){
       return 'hello world';
   }
}
Run Code Online (Sandbox Code Playgroud)

如果有任何疑问,请告诉我,如果有效,请接受答案:)