Run a function before sending email in contact form 7

Contact Form 7 is one of the most popular form management plugins available on WordPress repository. Which provide user friendly interface for managing form and email body. We can also manage addition settings like success or failure message form redirection etc in plugin settings.

We have on_sent_ok and wpcf7_before_send_mail which allow us to run our own custom commands before and after form submission. on_sent_ok is a JavaScript action hook. By using this hook, you can specify a JavaScript code that you wish to run after the form is successfully submitted. You will find the Additional Settings field at the bottom of the contact form page. Simply insert the following line into it

on_sent_ok: "location = 'http://example.com/';" 

I recently needed to create a function that needed to send sms to website owner for calling their executive to the visitor using Contact Form 7.

The code below creates a similar custom function before a Contact form 7 form is submitted. We need to add this code in theme’s functions.php file, adding the wpcf7_before_send_mail hook as an add_action call.

add_action('wpcf7_before_send_mail', 'my_custom_function');
 
function my_custom_function($cf7) {
    //Put PHP here
}

One thing to remember if you try and use echo to try and show any output, this will not be displayed because Contact Form 7 is designed to work using AJAX commands that execute PHP.

If you want to use form field data, we can grab this using regular $_POST variables as below:

	
add_action( 'wpcf7_before_send_mail', 'my_custom_function' );
 
function my_custom_function($cf7) {
   $output = "";
   $output .= "Name: " . $_POST['name'];
   $output .= "Email: " . $_POST['email'];
   $output .= "Message: " . $_POST['message'];
 
 file_put_contents("putoutput.txt", $output);
}

In this example, I have used file_put_contents php function which save form submitted data as a regular text in text file. The file is saved in the WordPress site root directory.