发送前如何连接到 Contact Form 7

How to hook into Contact Form 7 Before Send

我正在编写一个插件,我想与 Contact Form 7 进行交互。 在我的插件中,我添加了以下操作 add_action

add_action("wpcf7_before_send_mail", "wpcf7_do_something_else");

function wpcf7_do_something_else(&$wpcf7_data) {

    // Here is the variable where the data are stored!
    var_dump($wpcf7_data);

    // If you want to skip mailing the data, you can do it...
    $wpcf7_data->skip_mail = true;

}

我提交了联系表,但 add_action 我什么也没做。 当 Contact Form 7 时,我不确定如何让我的插件拦截或执行某些操作 做某事。任何帮助如何做到这一点?

我不得不这样做以防止发送电子邮件。希望对你有帮助。

/*
    Prevent the email sending step for specific form
*/
add_action("wpcf7_before_send_mail", "wpcf7_do_something_else");  
function wpcf7_do_something_else($cf7) {
    // get the contact form object
    $wpcf = WPCF7_ContactForm::get_current();

    // if you wanna check the ID of the Form $wpcf->id

    if (/*Perform check here*/) {
        // If you want to skip mailing the data, you can do it...  
        $wpcf->skip_mail = true;    
    }

    return $wpcf;
}

此代码假定您是 运行 最新版本的 CF7 您上面的代码过去一直有效,直到几个月前他们对代码进行了一些重构。 [2015 年 4 月 28 日]

我想补充一点,您可以只使用 wpcf7_skip_mail 过滤器:

add_filter( 'wpcf7_skip_mail', 'maybe_skip_mail', 10, 2 );

function maybe_skip_mail( $skip_mail, $contact_form ) {

    if( /* your condition */ )
        $skip_mail = true;

    return $skip_mail;

}

您可以在其他设置中打开演示模式,这将阻止发送电子邮件。请参阅下面的 CF7 文档。

If you set demo_mode: on in the Additional Settings field, the contact form will be in the demo mode. In this mode, the contact form will skip the process of sending mail and just display “completed successfully” as a response message.

自 WPCF7 5.2 以来,wpcf7_before_send_mail 挂钩发生了很大变化。作为参考,以下是如何在 5.2+

中使用此挂钩

跳过邮件

function my_skip_mail() {
    return true; // true skips sending the email
}
add_filter('wpcf7_skip_mail','my_skip_mail');

或将 skip_mail 添加到管理区域中表单的“其他设置”选项卡。

获取表单 ID 或 Post ID

function wpcf7_before_send_mail_function( $contact_form, $abort, $submission ) {

    $post_id = $submission->get_meta('container_post_id');
    $form_id = $contact_form->id();

    // do something       

    return $contact_form;
    
}
add_filter( 'wpcf7_before_send_mail', 'wpcf7_before_send_mail_function', 10, 3 );

获取用户输入的数据

function wpcf7_before_send_mail_function( $contact_form, $abort, $submission ) {

    $your_name = $submission->get_posted_data('your-field-name');

    // do something       

    return $contact_form;
    
}
add_filter( 'wpcf7_before_send_mail', 'wpcf7_before_send_mail_function', 10, 3 );

将电子邮件发送给动态收件人

function wpcf7_before_send_mail_function( $contact_form, $abort, $submission ) {

    $dynamic_email = 'email@email.com'; // get your email address...

    $properties = $contact_form->get_properties();
    $properties['mail']['recipient'] = $dynamic_email;
    $contact_form->set_properties($properties);

    return $contact_form;
    
}
add_filter( 'wpcf7_before_send_mail', 'wpcf7_before_send_mail_function', 10, 3 );