Dynamic populating drop down


I’d like to populate a field dinamically with “?post_type=tour” list.
I follow the docs and added this to function.php, but what I have to add in parameter name in Advanced-Parameter name in the form?

add_filter(  'gform_pre_render_myformID' ,  'populate_posts' );
add_filter(  'gform_pre_validation_myformID' ,  'populate_posts' );
add_filter(  'gform_pre_submission_filter_myformID' ,  'populate_posts' );
add_filter(  'gform_admin_pre_render_myformID' ,  'populate_posts' );
function populate_posts(  $form ) {
     foreach (  $form [ 'fields' ]  as & $field ) {
         if (  $field ->type !=  'select' ||  strpos (  $field ->cssClass,  'populate-posts' ) === false ) {
             continue ;
         // you can add additional parameters here to alter the posts that are retrieved
         // more info: http://codex.wordpress.org/Template_Tags/get_posts
         $posts = get_posts(  'numberposts=-1&post_status=publish' );
         $choices =  array ();
         foreach (  $posts as $post ) {
             $choices [] =  array (  'text' =>  $post ->post_title,  'value' =>  $post ->post_title );
         // update 'Select a Post' to whatever you'd like the instructive option to be
         $field ->placeholder =  'Select a Post' ;
         $field ->choices =  $choices ;
     return $form ;


The code is looking for the Custom CSS Class populate-posts (it’s in this line):

if ( $field ->type != 'select' || strpos ( $field ->cssClass, 'populate-posts' ) === false ) {

That line says “If the field type is NOT a select box OR the Custom CSS Class is NOT populate-posts” then skip all the code.

So, it’s not the dynamic population parameter name, but the Custom CSS Class name that should be set the populate-posts.

You’re also going to need to check for the post_type=‘tour’. Change this line:

$posts = get_posts( 'numberposts=-1&post_status=publish' );

Revised (for tours only):
$posts = get_posts( 'numberposts=-1&post_type=tour&post_status=publish' );

If you have any other questions, please let us know.

1 Like

Hi, thanks for reply.

Maybe I went wrong: I’d like to set a drop-down menu with my tour list (tour list is like article list in wordpress), so I can choose one of this tours as value for the field.

Is it possible?

Hi Lorenzo. That’s what the code will do. If you need more assistance, I recommend opening a support ticket: https://www.gravityforms.com/open-support-ticket/

Lorenzo, check https://gravitywiz.com/documentation/gravity-forms-populate-anything/ for a no-code solution.


Thanks @lkraav