首页 文章

方法POST的Wordpress REST API自定义 endpoints

提问于
浏览
0

我目前正在开发一个需要WordPress网站和简单REST api的项目 . 我发现WordPress有自己的REST api,并决定扩展其功能以满足我的需求 . 我需要做的就是为GET和POST请求提供 endpoints ,这些 endpoints 从/向与WordPress没有直接关系的表(但在同一个数据库中)检索/插入数据 . 我成功实现了所有GET请求,但是,我正努力让POST工作正常 .
我有这个路由寄存器定义:

register_rest_route('api/v1', 'create-player/', array(
        'methods' => 'POST',
        'callback' => 'create_player',
));

客户端通过ajax调用发送请求,该调用有望从上面的路由到达 endpoints . 这是ajax:

$.ajax({
       method: "POST",
       url: '/wp-json/api/v1/create-player/',
       data : JSON.stringify(data),
       contentType: 'applcation/json',
       beforeSend: function (xhr){
           xhr.setRequestHeader("X-WP-None", locData.nonce);
           console.log('beforeSend');
       },
       success: function(response){
           console.log("success" + response);
       },
       fail: function (response){
           console.log("fail" + response);
       }
    });

我不确定如何从REST api构建POST路由寄存器,其他GET请求具有直接映射到 endpoints 中传递的参数的属性 args . 使用POST时,我是否需要类似的东西来处理请求数据?如何获取从ajax传递的数据类型,然后在我的函数中使用 create_player(); WP REST API文档似乎不完整,我发现的所有信息都使用内置WordPress功能的 endpoints ,如帖子/作者/博客等等,但我不需要,我只想使用提供的功能并创建自己的界面 . 谢谢 .

2 回答

  • 6

    在你的回调函数中你可以使用这样的东西:

    $param = $request->get_param( 'some_param' );
    
      // You can get the combined, merged set of parameters:
     $parameters = $request->get_params();
    

    https://www.coditty.com/code/wordpress-api-custom-route-access-post-parameters

  • 5

    终于找到了!要访问POST请求的正文,请在 register_rest_route 回调方法中使用 $request->get_body(); .

相关问题