Executing a function before CONTACT FORM 7 send a mail.

Contact Form 7 is one of the most popular form management plugins available to WordPress, but it can be a little tricky when you need to extend the functionality beyond the default available options.
Fortunately, we have on_sent_ok and wpcf7_before_send_mail which allow us to run our own custom commands before and after form submission.
For example, I recently needed to create a function that automatically saves the data in the same database where wordpress is installed.

The code below show a similar custom function before a Contact form 7 form is submitted. This code needs to be added to the theme’s function.php file.


add_action('wpcf7_before_send_mail', 'save_in_database');

function save_in_database() {
     //Put PHP here
}

One thing to note is that if you try and use echo to try and show any output, this will not be displayed which could look like the function isn’t being triggered. This is due to how 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:


function save_in_database() {
     global $wpdb;
     $wpdb->show_errors();
     $name = mysqli_real_escape_string($_POST['name']);
     $email = mysqli_real_escape_string($_POST['email']);
     $phone = mysqli_real_escape_string($_POST['phone']);
     $message = mysqli_real_escape_string($_POST['message']);

     $wpdb->insert(
          'wp_contact',
          array(
               'name' => $name,
               'email' => $email,
               'phone' => $phone,
               'message' => $message
          ),
          array(
               '%s',
               '%s',
               '%s',
               '%s',
               '%s'
          )
     );

     $insert_id = $wpdb->insert_id;
}

In this example, we have been able to save the contact form data to the wp_contact table in the wordpress installation database using wordpress $wpdb->insert(). Click here to learn more about $wpdb->insert().

Know a better way? Please share in the comments box below 🙂