August 25, 2021
Two examples provided comparing the regular select and multi-select field functions for Gravity Forms.
Place in functions.php. Update filter number with the form ID.
Simple Select field function
// meal plans - individual meals
add_filter( 'gform_pre_render_3', 'populate_select' );
add_filter( 'gform_pre_validation_3', 'populate_select' );
add_filter( 'gform_pre_submission_filter_3', 'populate_select' );
add_filter( 'gform_admin_pre_render_3', 'populate_select' );
function populate_select( $form ) {
foreach( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'custom-class' ) === false ) { // change to the type of field you are using (checkbox = select, radio = choices, etc)
continue;
}
$args = array(
'post_type'=>'post',
'posts_per_page'=>-1,
);
$posts = get_posts( $args );
$choices = array();
$input_id = 1;
foreach ( $posts as $post ) {
$choices[] = array(
'text' => $post->post_title,
'value' => $post->post_title
);
$inputs[] = array(
'label' => $post->post_title,
'id' => "{$field->id}.{$input_id}"
);
$input_id++;
}
// update 'Select a Post' to whatever you'd like the instructive option to be
$field->placeholder = 'Select';
$field->choices = $choices;
$field->inputs = $inputs;
}
return $form;
}
Multi-Select field function
// meal plans - individual meals
add_filter( 'gform_pre_render_8', 'populate_select_multi' );
add_filter( 'gform_pre_validation_8', 'populate_select_multi' );
add_filter( 'gform_pre_submission_filter_8', 'populate_select_multi' );
add_filter( 'gform_admin_pre_render_8', 'populate_select_multi' );
function populate_select_multi( $form ) {
foreach( $form['fields'] as &$field ) {
if ( $field->type != 'multiselect' || strpos( $field->cssClass, 'custom-class' ) === false ) {
continue;
}
$args = array(
'post_type'=>'post',
'posts_per_page'=>-1,
);
$posts = get_posts( $args );
$choices = array();
foreach ( $posts as $post ) {
$choices[] = array(
'text' => $post->post_title,
'value' => $post->post_title,
'isSelected' => false
);
}
// update 'Select a Post' to whatever you'd like the instructive option to be
$field->placeholder = 'Select';
$field->choices = $choices;
}
return $form;
}