How do I check if email submitted via Contact form 7 exists in my database?

做~自己de王妃 提交于 2019-12-04 17:19:54
d79

I've added a filter on validation:

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

In this case the email field is named your-email.

The function email_exists is a native WP function to handle this.

Here is a solution that is working for me with the plugin 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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!