Halloween Sale 15% off Ends in See the plans
PHP

Fill Gravity Forms Fields With the Logged-In User's Details

Lets Gravity Forms fields fill themselves with the visitor's name, email, username or role when they are logged in, using simple parameter names.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_gf_user_params = array(
    'user_email'        => 'user_email',
    'user_first_name'   => 'first_name',
    'user_last_name'    => 'last_name',
    'user_display_name' => 'display_name',
    'user_login'        => 'user_login',
);

foreach ( $wpide_gf_user_params as $wpide_param => $wpide_prop ) {
    add_filter( 'gform_field_value_' . $wpide_param, function ( $value ) use ( $wpide_prop ) {
        if ( '' !== (string) $value || ! is_user_logged_in() ) {
            return $value;
        }

        return (string) wp_get_current_user()->get( $wpide_prop );
    } );
}

add_filter( 'gform_field_value_user_role', function ( $value ) {
    if ( '' !== (string) $value || ! is_user_logged_in() ) {
        return $value;
    }

    $roles = (array) wp_get_current_user()->roles;

    return $roles ? (string) reset( $roles ) : '';
} );

Notes

In a field's Advanced tab tick "Allow field to be populated dynamically" and enter one of the parameter names: user_email, user_first_name, user_last_name, user_display_name, user_login or user_role.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.