有没有办法在高级自定义字段上使用自定义验证?例如,我可能不希望textfield的值以某个前缀开头,或者我可能希望数字字段的值大于“x”。我可能还想对一个值运行正则表达式,如果不匹配,则返回一个错误。
高级自定义字段验证
4 个回复
最合适的回答,由SO网友:doublesharp 整理而成
现在,我刚刚将一个插件发布到Wordpress存储库中,该插件是我为高级自定义字段进行验证而编写的。它允许您使用PHP代码或regex、jQuery屏蔽输入以及唯一值设置进行服务器端验证。
http://wordpress.org/extend/plugins/validated-field-for-acf/
SO网友:Jake
我通过插入acf/pre_save_post
. 使用它,您可以测试$\\u POST数据。如果您不喜欢某些内容,可以在返回时将$post\\u id更改为“error”。这将阻止处理表单,因为post\\u id不正确。您还可以插入到acf/save_post
确保从表单中取消设置“返回”或更新消息。
这一切都有点复杂,但我将尝试给出一个我使用的简化示例。
$submitted_fields = \'\';
$validation_errors = \'\';
add_filter( \'acf/pre_save_post\', \'custom_validation\' );
function custom_validation( $post_id )
{
// Load the fields from $_POST
if ( empty($_POST[\'fields\']) || ! is_array($_POST[\'fields\']) )
{
$validation_errors[\'empty\'] = "One or more fields below are required";
}
else
{
foreach( $_POST[\'fields\'] as $k => $v )
{
// get field
$f = apply_filters(\'acf/load_field\', false, $k );
$f[\'value\'] = $v;
$submitted_fields[$f[\'name\']] = $f;
}
}
// Test stuff...
if ( empty($submitted_fields[\'foo\']) || \'bar\' != $submitted_fields[\'foo\'] )
{
$validation_errors[\'foo\'] = "Foo did not equal bar";
}
// If there are errors, output them, keep the form from processing, and remove any redirect
if ( $validation_errors )
{
// Output the messges area on the form
add_filter( \'acf/get_post_id\', array(__CLASS__, \'add_error\') );
// Turn the post_id into an error
$post_id = \'error\';
// Add submitted values to fields
add_action(\'acf/create_fields\', array(__CLASS__, \'acf_create_fields\'), 10, 2 );
}
else
{
// Do something... do nothing... ?
}
// return the new ID
return $post_id;
}
function acf_create_fields( $fields, $post_id )
{
foreach ( $fields as &$field )
{
if ( array_key_exists($field[\'name\'], $submitted_fields) )
$field[\'value\'] = $submitted_fields[$field[\'name\']];
}
return $fields;
}
function add_error()
{
echo \'<div id="message" class="error">\';
foreach ( $validation_errors as $key => $error )
{
echo \'<p class="\' . $key . \'">\' . $error . \'</p>\';
}
echo \'</div>\';
}
add_action(\'acf/save_post\', \'custom_handle_error\', 1);
function custom_handle_error( $post_id )
{
if ( \'error\' == $post_id )
{
unset($_POST[\'return\']);
}
}
这不允许突出显示返回错误的字段,但实际上,您可以使用javascript使用#message
部门。SO网友:That Brazilian Guy
从5.0版开始,您可以使用acf/validate_value
过滤器-请参阅official documentation.
SO网友:Wael Mahmoud
您可以使用此代码
add_filter(\'acf/validate_value/name=validate_this_image\', \'my_acf_validate_value\', 10, 4);
function my_acf_validate_value( $valid, $value, $field, $input ){
// bail early if value is already invalid
if( !$valid ) {
return $valid;
}
// load image data
$data = wp_get_attachment_image_src( $value, \'full\' );
$width = $data[1];
$height = $data[2];
if( $width < 960 ) {
$valid = \'Image must be at least 960px wide\';
}
// return
return $valid;
}
结果
结束