How to add an endpoint to WP

时间:2017-12-08 作者:Leff

我想知道如何添加一个端点来返回忍者表单插件数据。我制作了一个函数,从忍者表格中获取数据:

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

function getNinjaFormData(WP_REST_Request $request) {
    $id = $request->get_param(\'id\');
    $settings = [\'label\', \'type\', \'required\'];
    $formFields = Ninja_Forms()->form(1)->get_fields();
    $data = [];

    foreach ($formFields as $formField) {
      $key = $formField->get_setting(\'key\');
      foreach ($settings as $setting) {
        $data[$key][] = $formField->get_setting($setting);
      }
    }

    return $data;
  }
});

add_action( \'rest_api_init\', function () {
  register_rest_route( \'ninja-forms/\', \'/id/(?P<id>\\d+)\', array(
    \'methods\' => \'GET\',
    \'callback\' => \'getNinjaFormData\',
  ));
});
但是,这不起作用,我做错了什么?

1 个回复
SO网友:Jack Song

您需要返回WP\\u REST\\u响应对象。按以下方式编辑代码:

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

function getNinjaFormData(WP_REST_Request $request) {
    $id = $request->get_param(\'id\');
    $settings = [\'label\', \'type\', \'required\'];
    $formFields = Ninja_Forms()->form(1)->get_fields();
    $data = [];

    foreach ($formFields as $formField) {
      $key = $formField->get_setting(\'key\');
      foreach ($settings as $setting) {
        $data[$key][] = $formField->get_setting($setting);
      }
    }

    return new WP_REST_Response( $data, 200 );
  }
});

add_action( \'rest_api_init\', function () {
  register_rest_route( \'ninja-forms/\', \'/id/(?P<id>\\d+)\', array(
    \'methods\' => \'GET\',
    \'callback\' => \'getNinjaFormData\',
  ));
});

结束

相关推荐

Php致命错误:无法将WP_REST_RESPONSE类型的对象用作wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php中

我向WordPress添加了一个自定义端点,如下所示: add_action( \'rest_api_init\', function () { register_rest_route( \'menc/v1\', \'/crosscat/(?P[\\w-]+)/(?P[\\w-]+)\', array( \'methods\' => \'GET\', \'callback\' => \'dept_cat_api\',&#x