php - Contact Form 7 防止重复字段值提交

标签 php wordpress duplicates contact-form-7

我正在使用 WordPress 3.8 和带有 contact form 7 db 扩展名的 contact form 7 插件。

我想检查我在 functions.php 中的钩子(Hook) (alter_wpcf7_posted_data) 上提交的现有电子邮件,如下所示:

function alter_wpcf7_posted_data( $data ) {

    global $wpcf7;

    if(email_exists( $_POST['mail'])) {
            $data = array();
    }

return $data;
}
add_filter("wpcf7_posted_data", "alter_wpcf7_posted_data");

这个钩子(Hook)在源上抛出一个错误但不保存数据。

基本上,如果 email_exists() 返回 true,我不希望保存数据并在表单上抛出验证错误。

有谁知道如何防止表单提交。

注意:我没有使用 AJAX 表单提交。

最佳答案

我找到了解决方案。只需将此代码添加到您的 function.php

/**
 * @param $formName string
 * @param $fieldName string
 * @param $fieldValue string
 * @return bool
 */
function is_already_submitted($formName, $fieldName, $fieldValue) {
    require_once(ABSPATH . 'wp-content/plugins/contact-form-7-to-database-extension/CFDBFormIterator.php');
    $exp = new CFDBFormIterator();
    $atts = array();
    $atts['show'] = $fieldName;
    $atts['filter'] = "$fieldName=$fieldValue";
    $atts['unbuffered'] = 'true';
    $exp->export($formName, $atts);
    $found = false;
    while ($row = $exp->nextRow()) {
        $found = true;
    }
    return $found;
}

/**
 * @param $result WPCF7_Validation
 * @param $tag array
 * @return WPCF7_Validation
 */
function my_validate_email($result, $tag) {
    $formName = 'email_form'; // Change to name of the form containing this field
    $fieldName = 'email_123'; // Change to your form's unique field name
    $errorMessage = 'Email has already been submitted'; // Change to your error message
    $name = $tag['name'];
    if ($name == $fieldName) {
        if (is_already_submitted($formName, $fieldName, $_POST[$name])) {
            $result->invalidate($tag, $errorMessage);
        }
    }
    return $result;
}

// use the next line if your field is a **required email** field on your form
add_filter('wpcf7_validate_email*', 'my_validate_email', 10, 2);
// use the next line if your field is an **email** field not required on your form
add_filter('wpcf7_validate_email', 'my_validate_email', 10, 2);

// use the next line if your field is a **required text** field
add_filter('wpcf7_validate_text*', 'my_validate_email', 10, 2);
// use the next line if your field is a **text** field field not required on your form 
add_filter('wpcf7_validate_text', 'my_validate_email', 10, 2);

请记住将 email_form 更改为您的联系表单名称,并将 email_123 更改为电子邮件字段名称。使用 WordPress 4.9.5 和 CF7 5.0.1 对我来说工作得很好

关于php - Contact Form 7 防止重复字段值提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23564142/

相关文章:

javascript - 将 SmoothState.js 与 Wordpress 结合使用,但维护主体类

php - 检查数据库中是否已存在变量数据

php - 是多维数组好还是多维数组好?

php - [PHP][MySQL] 如何同时向2个表插入数据?

php - 如何正确缩进 PHP/HTML 混合代码?

duplicates - XmlPad 与 XPath 查找重复节点的问题

php - 多表JOIN返回重复结果,类似facebook的事件墙

php - 魔术报价关闭,仍然斜线

php - 可重复使用的自定义 WordPress 元框

css - 如何将产品标题放入产品缩略图