這裏的工作示例如何在聯繫表格7中實施一些自定義驗證和返回錯誤:
假設我們在我們的形式有此輸入字段:
<p>Your Name (required)<br />
[text* your-name] </p>
我們將它添加到我們的主題的functions.php文件:
// our function will be called for all text and text* input fields
add_filter('wpcf7_validate_text', 'wpcs4948_validation_func', 10, 2);
add_filter('wpcf7_validate_text*', 'wpcs4948_validation_func', 10, 2);
function wpcs4948_validation_func($result, $tag) {
$type = $tag['type'];
$name = $tag['name'];
// check to see if the input field name matches
if ('your-name' == $name) {
$the_value = $_POST[$name];
// use a regular expression to compare the value against
if (preg_match('/^\D*$/', $the_value)==0) {
// the value does not match the regular expression
// invalidate the form submission and display this error message
$result->invalidate($tag, "Name must contain only letters.");
}
}
return $result;
}
如果your-name
字段包含數字這將返回一個錯誤。
請注意,我沒有使用您建議的正則表達式/^[A-Za-z .]*$/
這是因爲該正則表達式會拒絕在其中包含破折號和句點的名稱,這可能不是您想要用於「名稱」字段的名稱。然而,如果你真的有興趣過濾一個「用戶名」字段只包含字母,比你可以用/^[A-Za-z .]*$/
替換/^\D*$/
希望這有助於!
應用過濾器只需要2個參數:https://developer.wordpress.org/reference/functions/apply_filters/ – Tdelang