If you need to send data from a Contact Form 7 (CF7) form to another URL you can use this simple PHP script. Just add it in your WordPress functions.php file inside your theme.
// define the URL where data should be submitted, this constant can be stored in your `wp-config.php` file define('CF7_TO_API_URL', 'https://...........'); function action_wpcf7_mail_sent( $contact_form ) { // you can limit this script to certains forms, just change the IDs (111,222,333) and uncomment line 10 and 47 // if (in_array($WPCF7_ContactForm->id(), [111,222,333])) { $wpcf7 = WPCF7_ContactForm::get_current(); $submission = WPCF7_Submission::get_instance(); if ($submission) { $data = $submission->get_posted_data(); $url = $submission->get_meta( 'url' ); // url where the submit come from $postId = url_to_postid($url); // from the url we get the post ID $postType = get_post_type($postId); // from post ID we get the post type $title = get_the_title($postId); // and the title $output = [ "firstname" => $data['firstname'], "lastname" => $data['lastname'], "email" => $data['email'], "phone" => $data['phone'], // add all needed fields "source" => $url, "is_product" => $postType === 'product', // ex: we want to know if the page was a product (custom post) "product_name" => $postType === 'product' ? $title : '', // if it is a product tell me the product name (title) "want_newsletter" => $data['newsletter'] === 1 || $data['newsletter'] === "1" // ex. for checkbox ]; $options = array( 'http' => array( 'method' => 'POST', // you can change the method (GET, POST) 'content' => json_encode( $output ), // php array as json 'header'=> "Content-Type: application/json\r\n" . "Accept: application/json\r\n" ) ); $context = stream_context_create( $options ); $result = file_get_contents( CF7_TO_API_URL, false, $context ); $response = json_decode( $result ); // you can use/output the response from } // } }; // add the action add_action( 'wpcf7_mail_sent', 'action_wpcf7_mail_sent', 10, 1 );
Hi! Thanks for tut. I have a form that needs to send data to an app server to create a test account. now if the email already registered, I need to show validation msg, can you please teach me how to retrieve server validation with this form?
Thanks in advance :)
Thank you :)
You can use
wpcf7_before_send_mail
orwpcf7_skip_mail
PHP hooks and there check if user is registered and then block the request.https://stackoverflow.com/questions/29926252/how-to-hook-into-contact-form-7-before-send
code reference: https://plugins.trac.wordpress.org/browser/contact-form-7/trunk/includes/submission.php?rev=1804687#L294
Or you can use DOM events to do the same with AJAX requests for example.
https://contactform7.com/dom-events/
Regards :)
Hi Diego
Excellent work
But, I have a problem, once I insert the code in my function file and submit the form, it is waiting and I do not receive any response from the form, do you understand me?
Maybe you can help me.
Regards,
Damian