Search code examples
phpwordpresscontact-form-7

Contact Form 7 submit failed validation


I need Contact Form 7 to send one email when validation has been failed. Then send the normal CF7 email when the form is submitted correctly. Ridiculous I know but clients!

I think I'm relatively close with the following:

function send_failed_vaildation_email( $data ) {
    $messagesend = 'Name:' . $_POST['your-name']; 
    $messagesend .= '\r\nEmail:' .$_POST['email']; 
    $messagesend .= '\r\nPhone:' .$_POST['validPhone']; 
    $messagesend .= '\r\nRate:' .$_POST['rate']; 
    $messagesend .= '\r\nBased:' .$_POST['based']; 
    wp_mail('c******[email protected]', 'failed validation mail', $messagesend );
}
add_filter("wpcf7_posted_data", "send_failed_vaildation_email");

However this sends all submissions regardless if they pass or fail the validation.

wpcf7_before_send_mail is no good as it only fires once the submission passes validation.

I'm either looking for a different hook to use instead of wpcf7_posted_data that only fires when validation is failed or an if statement I can place around wp_mail for the same effect.

Thanks in advance


Solution

  • This is how I managed to get it working.

    @rnevius answer was failing because the wpcf7_posted_data filter is applied before the data is validated so nothing is invalid at that time.

    Combining @rnevius' answer with the wpcf7_submit filter and it works as expected.

    Full code:

    function send_failed_vaildation_email() {
        $submission = WPCF7_Submission::get_instance();
        $invalid_fields = $submission->get_invalid_fields();
    
        $posted_data = $submission->get_posted_data();
    
        if ( !empty( $invalid_fields ) ) {
            $messagesend = 'Name:' . $posted_data['your-name']; 
            $messagesend .= '\r\nEmail:' . $posted_data['email']; 
            $messagesend .= '\r\nPhone:' . $posted_data['validPhone']; 
            $messagesend .= '\r\nRate:'  . $posted_data['rate']; 
            $messagesend .= '\r\nBased:' . $posted_data['based']; 
            $messagesend .= count($invalid_fields); 
            wp_mail('c*******[email protected]', 'failed validation mail', $messagesend );
        }
    }
    add_filter("wpcf7_submit", "send_failed_vaildation_email");