Capture post data on form submit in Contact Form 7

Capture post data on form submit in Contact Form 7

Here’s one I came across recently, I had a client who wanted to allow customers to submit there own testimonials and have the ability to receive an email when this is submitted with the option to either approve or decline said testimonial. An easy task in itself, the problem being that it had to integrate into there existing testimonials plugin.

The solution? I decided to use a Contact Form 7 form to handle the actual user submission, this of course got emailed to the website owner but the actual testimonial itself needed to be added dynamically into the testimonial post type.

After a bit of searching through the Contact Form & Docs I came across a hook that would allow me to do just that, the hook is wpcf7_mail_sent – essentially this simply allows you to hook into the forms sending process so I was able to capture the data and manipulate it to my needs.

Ok, so how do we do this? for argument sake lets say we have a simple form called ‘myTestForm’ that simply captures first and last name, here is how you would capture this data, of course this can be scaled to any type of form. Simply add the following into your functions.php file:

add_action( 'wpcf7_mail_sent', 'your_wpcf7_mail_sent_function' ); 

function your_wpcf7_mail_sent_function( $contact_form ) {
    $title = $contact_form->title;
    $submission = WPCF7_Submission::get_instance();
  
    if ( $submission ) {
    	$posted_data = $submission->get_posted_data();
    }
      
     
 
   if ( 'myTestForm' == $title ) {
     
    	$firstName = $posted_data['first-name'];
    	$lastName = $posted_data['last-name'];
    	
    	/* Put your code here to manipulate the data - simples 😉 */
   }
}

There it is! – very easy way to capture Contact Form 7 data with just a few lines of code. If you are having issues with the above code, ensure that you have updated to the latest version of Contact Form 7.

Let me know how you get on, leave a comment below and I will try to help where I can, remember to share this post!

Menu Title