允许管理员在某些情况下使用 ACF 绕过必填字段?

Allow admin to bypass required fields in certain situations with ACF?

我使用 acf_form 创建了一个 ACF 前端表单;这些字段被添加到后端的 User 记录中;然而,由于此表单包含必填字段,这意味着管理员无法在后端对用户进行基本更改除非用户已填写此表单。

所以我想知道在某些情况下是否可以允许管理员绕过被要求填写必填字段的要求,如果可以,我该怎么做?

好的,找到了一种方法 - 这是一种针对 User 屏幕的方法,对于其他 post 类型可能有所不同。

我们不仅要禁用服务器端验证,还要禁用 客户端 端验证,为此,我们做一些像这样的事情:

add_action('acf/input/admin_head', 'my_acf_admin_head');

function my_acf_admin_head() {

    if (!function_exists('get_current_screen')) {
        return;
    }

    // Get current page/screen
    $screen = get_current_screen();

    // Get current user
    $user = wp_get_current_user();

    if (is_object($screen) and is_a($screen, 'WP_Screen')) {

        if (($screen->id == 'user-edit' or ($screen->id == 'user' and $screen->action == 'add')) and in_array('administrator', $user->roles)) {
            ?>
                <script type="text/javascript">
                    window.acf.validation.active = false;
                </script>
            <?php
        }

    }

}

这将向与我们的限定符相匹配的任何页面添加一些 Javascript 以禁用 ACF 客户端验证。

现在,要禁用后端验证,我们可以这样做:

add_action('acf/validate_save_post', 'my_acf_validate_save_post', 10, 0);

function my_acf_validate_save_post() {

    if (!function_exists('get_current_screen')) {
        return;
    }

    // Get current page/screen
    $screen = get_current_screen();

    // Get current user
    $user = wp_get_current_user();

    if (is_object($screen) and is_a($screen, 'WP_Screen')) {

        if (($screen->id == 'user-edit' or ($screen->id == 'user' and $screen->action == 'add')) and in_array('administrator', $user->roles)) {
            // clear all errors so they can bypass validation for user data
            acf_reset_validation_errors();
        }

    }

}

请注意,由于 get_current_screen() 并非始终可用,因此这些方法 支持前端表单。

另请注意,此代码肯定可以改进为更干,但我会把它留给你。 :)