I am using Contact Form 7 where I have two fields (amongst others) namely "Service" and "Applicant Pin". What I intend to do is, if some specific Services are chosen along with a matching Applicant Pin, I don't want the form to send email, rather redirect to another page. I have seen a lot of solutions but none work for me. Here is the last code I tried:
add_action( 'wpcf7_before_send_mail', 'wpcf7_check_redirection', 10, 1 );
function wpcf7_check_redirection( $contact_form ) {
//Get the form ID
$form_id = $contact_form->id();
if( $form_id == 2852 ) {
$submission = WPCF7_Submission::get_instance();
$cf7_data = $submission->get_posted_data();
$service = $cf7_data['service'];
$pincode = $cf7_data['applicant_pin'];
$saltLake = array(700064, 700091, 700097, 700098, 700105, 700106, 700059, 700101, 700135, 700102, 700157, 700159);
if ( (($service = "Full Package for Single") || ($service = "Full Package for Couples")) && ( in_array($pincode, $saltLake)) ) {
$contact_form->skip_mail = true;
wp_redirect("https://example.com/services/");
exit;
}
}
}
In the developer tools, under the network section, I see a 302 status and fetch / Redirect Type for https://example.com/wp-json/contact-form-7/v1/contact-forms/2852/feedback and the console shows an error
{
"code": "invalid_json",
"message": "The response is not a valid JSON response."
}
I am at my wits' end. Can someone please help me?
CodePudding user response:
In your version, it appears you tried to use the comparison function =
which is a setter (x will equal value), and not a comparison (if x is equal to value).
I've used the wpcf7_skip_mail
filter to prevent the mail, but also added the redirection script to include in the footer, using wpcf7mailsent
javascript event listener.
add_action( 'wpcf7_before_send_mail', 'wpcf7_check_redirection', 10, 1 );
function wpcf7_check_redirection( $contact_form ) {
if ( 2744 === $contact_form->id() ) {
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
$cf7_data = $submission->get_posted_data();
$service = $cf7_data['service'];
$pincode = $cf7_data['applicant_pin'];
$saltLake = array( 700064, 700091, 700097, 700098, 700105, 700106, 700059, 700101, 700135, 700102, 700157, 700159 );
if ( in_array( $service, array( 'Full Package for Single', 'Full Package for Couples' ), true ) && in_array( $pincode, $saltLake, true ) ) {
// Proper way to add skip mail.
add_filter( 'wpcf7_skip_mail', '__return_true' );
}
}
}
}
add_action( 'wp_print_footer_scripts', 'dd_add_cf7_redirect' );
function dd_add_cf7_redirect() {
if ( is_page( 123 ) ) { // replace with your page id.
?>
<script type="text/javascript">
document.addEventListener('wpcf7mailsent', function (event) {
// Redirect to your location.
location = 'https://www.example.com/your-redirect-uri/';
}, false);
</script>
<?php }
}