How to create Dynamic Ninja Forms Lists from Post Types

Update August 2017: Updated code for NinjaForms THREE

Ninja Forms is a great plugin to create any type of input forms for WordPress.

In addition to its basic features it also supports a range of filters giving you even more flexibility.

Hotel Rooms as custom post types

In my specific situation I want to create a booking form for a hotel website and automatically list all available rooms in the form.
The rooms are created as custom post types.
register_post_type( 'room', ...

Read more about custom post types in WordPress codex.

Create the form field

Before adding list items I have to create the form and the according field.
Now remember the Field Key because we need to find the correct field in our filter later.

filter code

The Ninja Forms Filter ninja_forms_render_options  is called before the form is shown to the user, so we add the list items here.
/******************************************
* SHOW ALL ROOMS IN FIELD WITH KEY "ROOMS"
******************************************/
add_filter( 'ninja_forms_render_options', function($options,$settings){
   if( $settings['key'] == 'rooms' ){
       $args = array(
           'post_type' => 'room',
           'orderby' => 'menu_order',
           'order' => 'ASC',
           'posts_per_page' => 100,
           'post_status' => 'publish'
       );
       $the_query = new WP_Query( $args ); 
       if ( $the_query->have_posts() ){
           global $post;
           while ( $the_query->have_posts() ){
               $the_query->the_post();
               $options[] = array('label' => get_the_title( ), 'value' => get_the_title( ));
           }
           wp_reset_postdata(); 
       }
   }
   return $options;
},10,2);

More about Ninja Forms

Send beautiful WordPress Ninja Forms notifications to your customers

34 Responses to “How to create Dynamic Ninja Forms Lists from Post Types”

  1. Max

    Hello. This post helped me a lot.
    But i still have a trouble. Every post of my site has the same form with list which is pre-populated by post titles (including current post). So, how can i preselect title of the current post in the list?

    • hannes

      You can store the ID of the current page in a variable
      $current_post_id = get_the_ID();
      and change the line
      'selected' => 0
      to
      'selected' => ($current_post_id==get_the_ID()?1:0)

      • Max

        Thanks for answer. But it didn’t work =(
        Before i asked, my idea was the same – store id of current post to var and put it to “selected” option.

  2. gs

    Hello,
    I am new to ninja forms and I would like to create a form containing a list with values retrieved from database.
    I found the above article “HOW TO CREATE DYNAMIC NINJA FORMS LISTS FROM POST TYPES” very useful. However, it would be appreciated if you can advise to which php files, the code for “register_post_type” and the function “function haet_prepopulate_forms” should be added.
    Thank you.

    • hannes

      Add the code to the functions.php of your (child-)theme

  3. Fadi Wissa

    I guess this filter ninja_forms_field is not being used anymore by NinjaForms, correct?
    I keep trying to use it but my corresponding filter function does not get called.

    Would you please confirm?

    • hannes

      Hello,
      the filter is still in use.
      Did you already switch to THREE? The new version is in beta an still has some bugs…
      If not… where did you add the function and can I have a look at your code?

  4. Lia

    Hi there,

    Thanks for this tutorial – very usefull!

    However, the options only appear in fron-end. When checking the submissions (edit submission page) in backend the dropdown list is empty. Any solutions for that?

    • hannes

      Hey Lia, sorry I’ve no solution for that. I didn’t need to select the values in backend.

    • Ivan

      Lia, did you find a way to list all available posts at the backend dropdown?

  5. Craig Watson

    Hi,

    Great article! Would this code work with a list of custom taxonomies? I could do with getting this to work with Job Categories from the WP Job Manager Plugin.

    Craig

    • hannes

      Hey Craig,
      the filter changed to ninja_forms_render_options in NinjaForms THREE, I’ll update the script soon.
      To list taxonomies you can use get_taxonomies() instead of WP_Query

  6. Rik Verhagen

    Hi Hannes,
    In november you said you will update to script for Ninja Forms 3. Did you got a new one already?
    Thanks!

    • hannes

      Thanks for the reminder. I updated the code.

  7. Rik Verhagen

    Ah, I already got it:

    function cpt_prepopulate_forms($options, $settings) {
    global $post;
    if( $settings[‘id’] == 1 ) // change to your field ID
    {
    $args = array(
    ‘post_type’ => ‘room’, // Change to your Custom Post type
    );
    $query = new WP_Query( $args );
    if ( $query->have_posts() )
    {
    $options = array();
    while ( $query->have_posts() )
    {
    $query->the_post();
    $options[] = array(
    ‘label’ => get_the_title(),
    ‘value’ => $post->post_name,
    ‘calc’ => null,
    ‘selected’ => 0
    );
    }
    }
    wp_reset_postdata();
    }
    return $options;
    }
    add_filter(‘ninja_forms_render_options’,’cpt_prepopulate_forms’, 10, 2);

    • hannes

      Sorry I saw this post too late… Already updated my code above

    • hannes

      Just duplicate the whole IF-statement from line 5 to line 22.

  8. Ivan

    Hello,
    How can I get the default list selection to be equal to the actual post title?
    I mean, if I visit the post with title “POST1”, I want see the POST1 selected already in the list field.

    • hannes

      Hey Evan, I have no tested the code, but you can try. Use the code above and add the following:

      add_filter('ninja_forms_render_default_value', function($default, $field_type, $settings){
      if( $settings['key'] == 'rooms' ){
      global $post;
      $default = $post->post_title;
      }
      return $default;
      },10,3);

      Of course you could extend the code to check whether a there is a value with this title.

  9. Ivan

    Hi Hannes,
    I edited your first code, but by now my code but I think is something wrong with my string comparison as its not comparing yet:

    add_filter( ‘ninja_forms_render_options’, function($options,$settings){
    if( $settings[‘key’] == ‘tours’ ){
    $args = array(
    ‘post_type’ => ‘tours’,
    ‘orderby’ => ‘menu_order’,
    ‘order’ => ‘ASC’,
    ‘posts_per_page’ => 100,
    ‘post_status’ => ‘publish’
    );
    $the_query = new WP_Query( $args );
    $default = $post->post_title; //current post title
    $selectionnumber = 0; //value initialization for selection counter
    if ( $the_query->have_posts() ){
    global $post;
    while ( $the_query->have_posts() ){

    $the_query->the_post();

    $options[] = array(‘label’ => get_the_title( ), ‘value’ => get_the_title( ), ‘selected’ => $selectionnumber);
    if ($default != get_the_title( )){ //if the current post title is different to while title
    $selectionnumber = $selectionnumber +1; //counter of posts berore the current post
    }
    }
    wp_reset_postdata();
    }
    }
    return $options;
    },10,2);

    • Ivan

      I fix it!!!
      But I have a question, what is the meaning of “,10,2” at the end of the code?

      here is the code:
      /******************************************
      * SHOW ALL tours IN FIELD WITH KEY “tours” in ninja form
      ******************************************/
      add_filter( ‘ninja_forms_render_options’, function($options,$settings){
      if( $settings[‘key’] == ‘tours’ ){
      $args = array(
      ‘post_type’ => ‘tours’,
      ‘orderby’ => ‘menu_order’,
      ‘order’ => ‘ASC’,
      ‘posts_per_page’ => 100,
      ‘post_status’ => ‘publish’
      );
      $the_query = new WP_Query( $args );

      if ( $the_query->have_posts() ){
      global $post;
      $default = $post->post_title; //current post title

      while ( $the_query->have_posts() ){

      $the_query->the_post();
      $actualtitle = get_the_title( );

      if ($default != $actualtitle ){ //if the current post title is different to while title
      $options[] = array(‘label’ => get_the_title( ), ‘value’ => get_the_title( ), ‘selected’ => 0);
      }
      else {
      $options[] = array(‘label’ => get_the_title( ), ‘value’ => get_the_title( ), ‘selected’ => 1);
      }

      }
      wp_reset_postdata();
      }
      }
      return $options;
      },10,2);

      • hannes

        10 is the priority of the filter (default value)
        2 is the number of parameters (default is 1)

  10. Diana Soijo

    Hi
    Thanks for the code!
    I am stuck with the meta-data. I want to add meta data form the wp_posts_meta table. Could you help me with that.

    • hannes

      Hello, if you want to show a meta field instead of the title replace
      get_the_title( )
      with
      get_post_meta( $post->ID, 'YOUR_META_FIELD', true )

  11. Diona

    Hi,
    The select field value is not populated on the ninja forms submission tab on the wp admin dashboard.Any ways that I could show them up??

    Thank you
    Diona

    • hannes

      Hello,
      I know this problem but I don’t have a solution, sorry. I just send the submissions via email and export them via Excel Export

  12. Tomas Strejcek

    Hi, I have been looking for a professional specialized in ninja form. It seems that I finaly found one. I am trying to create a custom function that will save (take in consideration previous value and add a new one) information from the form to the custom meta field in custom type called ‘hraci’ for a specific post id (winner, looser).

    From ninja form that has ID: 2

    when user hit submit button it will take informations from specific fields and save them to custom post type “hraci” and following custom metas

    ID of a winner can be found in a field from ninja form ‘idckoviteze’

    following fields save to that post ID

    field from ninja form: ‘vitezne_sety_vitez’ save to ‘wpcf-viteznesety’
    field from ninja form: ‘prohrane_sety_vitez’ save to ‘wpcf-prohranesety’
    field from ninja form: ‘pocet_viteznych_micu_vitez’ save to ‘wpcf-viteznemice’
    field from ninja form: ‘pocet_prohranych_micu_vitez’ save to ‘wpcf-prohranemice’
    field from ninja form: ‘zapoctivitezstvi’ save to ‘wpcf-vyhrycelkem’

    ID of a looser can be found in a field from ninja form ‘idckoporazeneho’

    following fields save to that post ID

    field from ninja form: ‘vitezne_sety_porazeny’ save to ‘wpcf-viteznesety’
    field from ninja form: ‘prohrane_sety_porazeny’ save to ‘wpcf-prohranesety’
    field from ninja form: ‘pocet_viteznych_micu_porazeny’ save to ‘wpcf-viteznemice’
    field from ninja form: ‘pocet_prohranych_micu_porazeny’ save to ‘wpcf-prohranemice’

    Do you think you would be able to help me with this? 🙂

    • Hannes

      Hey,
      That sounds tricky but I‘m sure it is possible.
      It is just more than a simple answer in a comment. Please send me an email to talk about a quote for this feature.
      Best regards, Hannes

  13. Adam

    This post and all the comments have been great and really helpful for my Ninja forms project, so thanks.

    I have successfully used the code to generate a drop down list using post titles from a specific post type. However, I have a couple of things that I’d like help on please.

    1) Is there a way to only show post titles from a specific category within the post type?

    2) Is there a way of displaying the content or data from custom fields from a specific post based on a selection from the drop down?

    For example, I have a post type of ‘location’ with categories of ‘cities’. I want to have a Ninja form drop down where the user can select a city and then in another Ninja form text field I want to display data from a custom field of ‘address’ from the selected post

    Hope you can help!?

    Many thanks.

    • Hannes

      Hey Adam,
      1. just change the WP_Query args. Selecting custom post types by a taxonomy should be documented here https://developer.wordpress.org/reference/classes/wp_query/

      2. for this use case you need to load field content dependent on another fields value so you need some Ajax calls. This wont be possible with the code above, I think this will be far more complicated.
      best regards, Hannes

      • Adam

        Many thanks for your very quick response Hannes! I’ll take a look.

  14. Pat

    Hi,
    I’m trying to implement it with ‘Select Image’ field but it didn’t work.

    Thanks