I am working on a site with several forms created using Contact Form 7. For one of these forms, I am passing variables that I collected using a hidden input field in the form. I am passing these variables into the email using the wpcf7_before_send_mail hook, but these values are passing into every email (I added dynamic variables as well as static text) Here's the code:
add_action( 'wpcf7_before_send_mail', 'wpcf7_add_text_to_mail_body' );
function wpcf7_add_text_to_mail_body($contact_form){
$values_list = $_POST['valsitems'];
$values_str = implode(", ", $values_list);
// get mail property
$mail = $contact_form->prop( 'mail' ); // returns array
// add content to email body
$mail['body'] .= 'INDUSTRIES SELECTED';
$mail['body'] .= $values_list;
// set mail property with changed value(s)
$contact_form->set_properties( array( 'mail' => $mail ) );
}
I am trying to figure out how to only pass these values to one of the contact form email templates, probably via the form id.
In Contact Form 7, a user-input validation is implemented as a filter function. The filter hook used for the validation varies depending on the type of form-tag and is determined as: wpcf7_validate_ + {type of the form-tag}. So, for text form-tags, the filter hook wpcf7_validate_text is used.
The wpcf7_before_send_mail is an action hook of this plugin that executes a function before sending the form data to the email. With wpcf7_before_send_mail action hook, you can call a PHP function after Contact Form 7 submit.
Publish the formSelect Contact → Contact Forms. Then copy the shortcode next to the form that you want to add to your site. Next, open the page or post where you would like to insert the contact form. Paste the shortcode in the text area of the post editor where you would like the contact form displayed.
Contact Form 7 uses hidden input type to store form id. It uses hidden field name _wpcf7. You can get the form Id like this way.
$form_id = $contact_form->posted_data['_wpcf7'];
So you final code should be
add_action( 'wpcf7_before_send_mail', 'wpcf7_add_text_to_mail_body' );
function wpcf7_add_text_to_mail_body($contact_form){
$form_id = $contact_form->posted_data['_wpcf7'];
if ($form_id == 123): // 123 => Your Form ID.
$values_list = $_POST['valsitems'];
$values_str = implode(", ", $values_list);
// get mail property
$mail = $contact_form->prop( 'mail' ); // returns array
// add content to email body
$mail['body'] .= 'INDUSTRIES SELECTED';
$mail['body'] .= $values_list;
// set mail property with changed value(s)
$contact_form->set_properties( array( 'mail' => $mail ) );
endif;
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With