如何在联系表格 7 中发送之前更改数据?

Iho*_*huk 2 php wordpress contact-form-7

我的网站上有联系表格。我需要在发送邮件之前更改一个字段的值。例如name。我像这样尝试:

function contactform7_before_send_mail( $cf7 ) {
    $cf7->posted_data['your_name'] = 'John Doe';
}

add_action( 'wpcf7_before_send_mail', 'contactform7_before_send_mail' );
Run Code Online (Sandbox Code Playgroud)

但是在电子邮件中出现了表单中指定的值。

Rim*_*arx 8

最近遇到了同样的问题。
例如,此表单中有一个名为“[s2-name]”的字段。当访问者提交表单时,我想获取此字段,然后更改并发送。经过一些信息搜索,我写了这段代码:

    add_action( 'wpcf7_before_send_mail', 'wpcf7_do_something_else_with_the_data', 90, 1 );
    
    function wpcf7_do_something_else_with_the_data( $WPCF7_ContactForm ){
    
        // Submission object, that generated when the user click the submit button.
        $submission = WPCF7_Submission :: get_instance();
    
        if ( $submission ){
            $posted_data = $submission->get_posted_data();      
            if ( empty( $posted_data ) ){ return; }
            
            // Got name data
            $name_data = $posted_data['s2-name'];
    
            // Do my code with this name
            $changed_name = 'something';
    
            // Got e-mail text
            $mail = $WPCF7_ContactForm->prop( 'mail' );
    
            // Replace "[s2-name]" field inside e-mail text
            $new_mail = str_replace( '[s2-name]', $changed_name, $mail );
    
            // Set
            $WPCF7_ContactForm->set_properties( array( 'mail' => $new_mail ) );
            
            return $WPCF7_ContactForm;
        }
    }
Run Code Online (Sandbox Code Playgroud)

测试:WP 5.4.2 和联系表 7 版本 5.2