Fill Gravity Forms Choices With Team Members
Fills a Gravity Forms drop-down or radio field with the names of users in a role, such as staff or agents, so visitors can choose who they want to contact.
Opens WPIDE on
Code
$wpide_gf_users = function ( $form ) {
foreach ( $form['fields'] as $field ) {
if ( ! in_array( $field->type, array( 'select', 'radio' ), true ) || ! preg_match( '/\bpopulate-role-([a-z0-9_-]+)\b/', (string) $field->cssClass, $m ) ) {
continue;
}
$users = get_users( array( 'role' => $m[1], 'orderby' => 'display_name', 'fields' => array( 'ID', 'display_name' ), 'number' => 200 ) );
$field->choices = array_map( function ( $user ) {
return array( 'text' => $user->display_name, 'value' => (string) $user->ID );
}, $users );
}
return $form;
};
add_filter( 'gform_pre_render', $wpide_gf_users );
add_filter( 'gform_pre_validation', $wpide_gf_users );
add_filter( 'gform_pre_submission_filter', $wpide_gf_users );
add_filter( 'gform_admin_pre_render', $wpide_gf_users );
Notes
Give the field the CSS class populate-role-<role> (for example populate-role-editor); values are user IDs, so pair it with a routing snippet if you email the chosen person.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.