我通过插入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
部门。