Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save snrjosh/f478ae682509973fe7029890ffacf0b4 to your computer and use it in GitHub Desktop.
Save snrjosh/f478ae682509973fe7029890ffacf0b4 to your computer and use it in GitHub Desktop.
Dynamically populate Gravity Forms Select field with ACF Select field choices
<?php
/*
* Dynamically populate Gravity Forms Select field with ACF Select field Choices
*
* Add form ID at end of each filter to target a specific form
*
* Ref: https://docs.gravityforms.com/dynamically-populating-drop-down-fields/
*
*/
//Target form with ID 2.
add_filter( 'gform_pre_render_2', 'populate_gf_select_from_acf_select' );
add_filter( 'gform_pre_validation_2', 'populate_gf_select_from_acf_select' );
add_filter( 'gform_pre_submission_filter_2', 'populate_gf_select_from_acf_select' );
add_filter( 'gform_admin_pre_render_2', 'populate_gf_select_from_acf_select' );
function populate_gf_select_from_acf_select( $form ) {
foreach ( $form['fields'] as &$field ) {
// Check if field type is a Select and ID is 8.
if ( $field->type == 'select' && $field->id == 8 ) {
// ACF select field object - use field key.
$acf_field = get_field_object( 'field_62261b6cbc90d' );
// Create blank array.
$choices = array();
if ( $acf_field ) {
// Loop over Select choices and add to $choices array.
foreach ( $acf_field['choices'] as $value => $label ) {
$choices[] = array( 'text' => $label, 'value' => $value );
}
}
// (Optional) Set placeholder text for GF dropdown.
$field->placeholder = 'Select a location';
// Set choices from array of ACF Select choices.
$field->choices = $choices;
}
}
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment