0

I am wondering how can I add an endpoint where I would return the ninja form plugin data. I have made a function where I am getting the data from the ninja form:

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',
  ));
});

But, this is not working, what am I doing wrong?

  • 1
    When asking for help, in general you should clarify "not working" by including the output of your existing code and explaining how it differs from what you expect. In this case I'm pretty sure I know the problem, but I have to guess because you haven't actually stated it yourself. – user66711 Dec 8 '17 at 18:20
0

You need to return a WP_REST_Response object. Edit your code like the following:

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',
  ));
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.