Populate a Gravity Forms Choice Field With User Roles

If you need to allow your users to be able to choose from a list of WordPress roles on your Gravity Form, this snippet is for you. It easily allows you to populate all the roles from your site into the choices on a field.

This includes the default WordPress roles (Admin, Editor etc), and custom roles that are added by third party plugins too.

One great use case for this is if you’re using the Gravity Forms User Registration Add-On, and want to allow your users to select their role.

// Change 123 to your form ID
add_filter( 'gform_pre_render_123', 'populate_user_roles' );
add_filter( 'gform_pre_validation_123', 'populate_user_roles' );
add_filter( 'gform_pre_submission_filter_123', 'populate_user_roles' );
add_filter( 'gform_admin_pre_render_123', 'populate_user_roles' );
function populate_user_roles( $form ) {

    // Update "4" to your choice field ID.
	$target_field_id = 4;
 
    foreach ( $form['fields'] as &$field ) {
 
        if ( $field->id != $target_field_id ) {
			continue;
		}
 
        $roles = wp_roles()->roles;
 
        $choices = array();
 
        foreach ( $roles as $role ) {
            $choices[] = array( 'text' => $role['name'], 'value' => $role['name'] );
        }
 
        $field->choices = $choices;
 
    }
 
    return $form;
}

Where to add the snippet?

Whichever snippet you choose to use, you should place it at the bottom of the functions.php file of your child theme. Make sure you know what you’re doing when editing this file. Alternatively, you can use a plugin such as Code Snippets to add the custom code to your WordPress site. If you need further guidance on how to add the code, check out our post on How to Add WordPress Snippets.