PHP 需要 WordPress 注册表单复选框

PHP WordPress register form required checkbox

我正在尝试使我的 WordPress 注册表符合 GDPR,用户需要勾选他们接受我们的隐私政策的复选框。

我已经使用钩子register_form成功创建了复选框。

但是,我在将复选框字段设为必填时遇到了问题。我已经尝试在我的数组中使用 required true 但它似乎不起作用。有人可以解释一下我可以做什么才能使复选框成为必填项吗?

add_action( 'register_form', 'login_extra_note' );

function login_extra_note() {

    woocommerce_form_field( 'privacy_policy_reg', array(
        'type'          => 'checkbox',
        'class'         => array('form-row privacy'),
        'label_class'   => array('label-for-checkbox checkbox'),
        'input_class'   => array('form__input-checkbox input-checkbox'),
        'required'      => true,
        'label'         => 'Jeg har læst og acceptere <a href="https://example.dk/privatliv/" target="blank">Betingelser & Privatlivspolitik</a>',
    ) );

}

此问题与没有错误消息关联到复选框字段有关。我设法通过在复选框字段中添加错误来解决它:

// add registration chekbox field
add_action( 'register_form', 'login_extra_note' );

function login_extra_note() {

woocommerce_form_field( 'privacy_policy_reg', array(
   'type'          => 'checkbox',
   'class'         => array('form-row privacy'),
   'label_class'   => array('label-for-checkbox checkbox'),
   'input_class'   => array('form__input-checkbox input-checkbox'),
   'required'      => true,
   'label'         => 'Jeg har læst og acceptere <a href="https://example.dk/privatliv/" target="blank">Betingelser & Privatlivspolitik</a>',
));

}

// Error registration form
function my_registrationform_error( $errors, $sanitized_user_login, $user_email ) {

    if ( ! (int) isset( $_POST['privacy_policy_reg'] ) ) {
    $errors->add( 'demo_error', __( '<strong>FEJL</strong>: Du skal accepter VIFT Betingelser & Privatlivspolitik!', 'my_textdomain' ) );
        }
    return $errors;
}

add_filter( 'registration_errors', 'my_registrationform_error', 10, 3 );