Halloween Sale 15% off Ends in See the plans
PHP

Prefill Contact Form 7 With the Logged-In User's Details

Fills the name and email fields of Contact Form 7 forms with the details of the logged-in visitor, so members do not have to type them again.

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

Code

// Form field name => user detail (display_name, user_email, first_name, last_name).
$wpide_cf7_user_map = array(
    'your-name'  => 'display_name',
    'your-email' => 'user_email',
);

add_filter( 'wpcf7_form_tag', function ( $tag ) use ( $wpide_cf7_user_map ) {
    if ( ! is_user_logged_in() || empty( $tag->name ) || ! isset( $wpide_cf7_user_map[ $tag->name ] ) || ! empty( $tag->values ) ) {
        return $tag;
    }

    $user  = wp_get_current_user();
    $value = (string) $user->get( $wpide_cf7_user_map[ $tag->name ] );

    if ( '' !== $value ) {
        $tag->values     = array( $value );
        $tag->raw_values = array( $value );
    }

    return $tag;
} );

Notes

Uses the default field names your-name and your-email; change the map at the top for your own field names.

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.