How To Update Contact Form 7 Field Before Mail Sent

In this tutorial I will show you what you need to do in order to update a contact form 7 field before mail sent. I needed to implement this feature because I had to get a code from a txt file and update a certain field with the new code.

How to implement a before mail send function

First of all you need to create a new function which will be triggered before the mail to be sent. The code is below:

add_action('wpcf7_before_send_mail', 'save_application_form');

function save_application_form($wpcf7){
  global $wpdb;
  $submission = WPCF7_Submission::get_instance();
}

If you add a die() in the above function and open up the developer console -> Network, you will see that when you click on submit button, contact form 7 won't send the mail because the script will be stopped due to the die() added in your function. Now, in order to update a field from our form before the mail to be sent we will need to change the above function, because the cf7 data is saved before the wpcf7_before_send_mail hook. So we will use the following code:

 

add_filter( 'wpcf7_posted_data', 'save_application_form', 10, 1 );
function save_application_form($array){
}

If you var_dump the $array parameter will you see that all data from the form is in that array. In other word to update the cf7 contact form we will have to add the following line of code:

$array["you_field"] = 'new value';
return $array;

With the above code you will can change any field you need. Let me know if you need any help with this implementation

4 1 vote
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Jacques
Jacques
4 years ago

I’m trying to use this code but it doesn’t work.
I have a field name ‘geoportail’ and I want to change everything that is sent to this field name to ‘toto’
Thanks
Jacques

2
0
Would love your thoughts, please comment.x
()
x