Many WordPress websites include user registration and login functionality, and it's nice to include the username of the person submitting the form. In this tutorial I will show you how to have the username automatically send with a Contact Form 7 form submission. If you don't know what Contact Form 7 is, it's a popular WordPress plugin that allows you to create custom email forms on your WordPress website.
Contact Form 7 has what are called 'Special Mail Tags' built in to the plugin. The user optionally enters these special mail tags into the 'Message body' section of the Contact Form 7 admin when creating and editing custom forms. In the tutorial below I will show you how to add a new custom 'Special Mail Tag' allowing you to include the logged in username in the form message.
Creating a custom 'username' Special Mail Tag in Contact Form 7
- Log into WordPress and make sure you have the Contact Form 7 plugin installed.
- Click on 'Plugins'.
- Click on 'Edit' under the 'Contact Form 7' plugin.
- Click on the link 'contact-form-7/modules/special-mail-tags.php' on the right side of the page.
- Somewhere in the source code enter this code snippet:
PHP | copy code | ? 01 02 add_filter( 'wpcf7_special_mail_tags', 'wpcf7_special_mail_tag_userdata', 10, 2 );
03 04 function wpcf7_special_mail_tag_userdata( $output, $name ) {
05 06 // For backwards compat.
07 $name = preg_replace( '/^wpcf7\./', '_', $name );
08 09 global $current_user;
10 11 if ( 'user_login' == $name )
12 $output = $current_user->user_login;
13 14 return $output;
15 }
- Click the 'Update File' button.
Make a form include the username of the logged in user
- Click on the 'Contact' tab.
- From the list of 'Contact Form 7' forms, click the one you want to edit so that the username sends with the form data.
- Enter the tag [user_login] somewhere in your 'Message body' field, and it will automatically be replaced with the username of the person sending the form, if they are logged in.
Example: "Username: [user_login] "
- Click the 'Save' button.