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

问题描述 投票:0回答:3

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

name
。我尝试这样:

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

add_action( 'wpcf7_before_send_mail', 'contactform7_before_send_mail' );

但是电子邮件中包含表单中指定的值。

php wordpress contact-form-7
3个回答
12
投票

最近遇到了同样的问题。
例如,此表单中有一个名为“[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;
        }
    }

测试使用:WP 5.4.2 和 Contact Form 7 版本 5.2


1
投票

试试这个:

post.php

    $_POST["your_name"] = "John Doe");
    do_shortcode("[cfdb-save-form-post]");

form.html

<form class="form-contact" action="post.php" method="post">
  <input type="text" name="your_name" />
</form>

0
投票

使用更具体的

wpcf7_posted_data
过滤器,而不是
wpcf7_before_send_mail
操作。

有关如何使用的示例,请参阅此答案

© www.soinside.com 2019 - 2024. All rights reserved.