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
  • 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, 2017 at 18:20

2 Answers 2

1

You need to return a WP_REST_Response object instead of an array.

See https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/ and https://developer.wordpress.org/reference/classes/wp_rest_response/.

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 and acknowledge that you have read and understand our privacy policy and code of conduct.

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