Add Visitor Details to Contact Form 7 Emails
Appends the page the form was sent from, the date, the visitor's browser and IP address to every Contact Form 7 email, without editing each form's mail template.
Opens WPIDE on
Code
add_filter( 'wpcf7_mail_components', function ( $components, $contact_form = null, $mail = null ) {
$submission = class_exists( 'WPCF7_Submission' ) ? WPCF7_Submission::get_instance() : null;
if ( ! $submission || ( $mail && method_exists( $mail, 'name' ) && 'mail' !== $mail->name() ) ) {
return $components;
}
$details = array(
'Page' => (string) $submission->get_meta( 'url' ),
'Date' => wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), (int) $submission->get_meta( 'timestamp' ) ),
'Browser' => (string) $submission->get_meta( 'user_agent' ),
'IP' => (string) $submission->get_meta( 'remote_ip' ),
);
$html = $mail && method_exists( $mail, 'get' ) && $mail->get( 'use_html' );
$text = '';
foreach ( $details as $label => $value ) {
$text .= $html ? '<br>' . esc_html( $label . ': ' . $value ) : "\n" . $label . ': ' . $value;
}
$components['body'] .= ( $html ? '<hr>' : "\n\n--" ) . $text;
return $components;
}, 10, 3 );
Notes
Applies to the main mail only, not the autoresponder; remove the IP line if your privacy policy does not cover it.
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.