Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

php - Contact Form 7: use hook created using wpcf7_before_send_mail for only one contact form by id

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...