Contact Form 7 有条件重定向而不发送邮件

Contact Form 7 Conditional Redirection Without Sending Mail

我正在使用联系表 7,其中有两个字段(除其他外),即“服务”和“申请人密码”。我打算做的是,如果选择了某些特定服务以及匹配的申请人 Pin,我不希望表单发送电子邮件,而是重定向到另一个页面。我见过很多解决方案,但 none 对我有用。这是我最后尝试的代码:

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;
                }
    }
    
}

在开发人员工具的网络部分下,我看到 https://example.com/wp-json/contact-form-7/v1/contact-forms/2852/feedback 的 302 状态和提取/重定向类型,控制台显示错误

{
    "code": "invalid_json",
    "message": "The response is not a valid JSON response."
}

我已经束手无策了。有人可以帮我吗?

在您的版本中,您似乎尝试使用比较函数 =,它是 setter(x 将等于值),而不是比较(如果 x 等于值) .

我使用 wpcf7_skip_mail 过滤器来阻止邮件,但也使用 wpcf7mailsent javascript 事件侦听器添加了重定向脚本以包含在页脚中。

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 }
}