如何检查通过联系表格7提交的电子邮件是否存在于我的数据库中?

时间:2015-04-08 01:30:27

标签: wordpress wordpress-plugin contact-form-7

当客户通过联系表单7提交电子邮件时,如何检查我的数据库中是否已存在电子邮件,并将通知消息更改为“您的电子邮件已存在于我们的数据库中”

到目前为止,我已经尝试过使用before_send钩子,但是当我点击提交时,页面只是挂起而没有确认消息。

以下是我在functions.php中的功能

add_action( 'wpcf7_before_send_mail', 'check_email' );

function check_email( $cf7 )
{
$email = $cf7->posted_data["email"];
if($email == 'Is in our database'){
echo ('Your email exists in our database');
}
}

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

我在验证中添加了一个过滤器:

add_filter( 'wpcf7_validate', 'email_already_in_db', 10, 2 );

function email_already_in_db ( $result, $tags ) {
    // retrieve the posted email
    $form  = WPCF7_Submission::get_instance();
    $email = $form->get_posted_data('your-email');
    // if already in database, invalidate
    if( email_exists( $email ) ) // email_exists is a WP function
        $result->invalidate('your-email', 'Your email exists in our database');
    // return the filtered value
    return $result;
}

在这种情况下,电子邮件字段名为your-email

函数email_exists是一个本机WP函数来处理这个问题。

答案 1 :(得分:0)

这是一个适用于我的插件Advanced Contact form 7 DB

的解决方案
function email_already_in_db ( $result, $tags ) {
    // Retrieve the posted form
    $form  = WPCF7_Submission::get_instance();
    $form_posted_data = $form->get_posted_data();

    // Get the field name that we want to check for duplicates.
    // I added 'unique' to the beginning of the field name in CF7
    // Checking for that with preg_grep
    $unique_field_name = preg_grep("/unique(\w+)/", array_keys($form_posted_data));

    // $unique_field_name comes back as array so the next three lines give us the key as a string
    reset($unique_field_name);
    $first_key = key($unique_field_name);
    $unique_field_name = $unique_field_name[$first_key];

    // Check the form submission unique field vs what is already in the database
    $email = $form->get_posted_data($unique_field_name);
    global $wpdb;
    $entry = $wpdb->get_results( "SELECT * FROM wp_cf7_vdata_entry WHERE name LIKE '$unique_field_name' AND value='$email'" );

    // If already in database, invalidate
    if (!empty($entry)) {
      $result->invalidate($field_name, 'Your email: '.$email.' already exists in our database.');
      }
    // return the filtered value
  return $result;
}