I'm currently working on the WooCommerce registration page in my WordPress theme and added a hook for users to accept the Terms & Conditions - see PHP code added.
HTML5 provides a super helpful feature for input fields, which is to add 'required' in the tag and new browser will automatically prompt a warning. I have managed to do this for all other input fields, but I'm unable to amend this specific PHP array to output the <input>
tag with the 'required'
attribute.
The HTML output would need to look like this:
<input required type="checkbox" class="input-checkbox woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="privacy_policy_reg" id="privacy_policy_reg" value="1">
However, at the moment the produced output based on the PHP code below is:
<input type="checkbox" class="input-checkbox woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="privacy_policy_reg" id="privacy_policy_reg" value="1">
Note: the hook already has a PHP validation check but only after the register button is pressed, while the HTML5 check works instantly. Nevertheless, I want to keep the PHP validation check in case there are browsers that cannot read the HTML5 check.
Could anyone kindly help me how the PHP array code would need to be amended to have the tag to include the 'required' attribute?
I'd very much appreciate any help!
Best, David
// CREATE CHECKBOX AND LABEL
add_action( 'woocommerce_register_form', 'bbloomer_add_registration_privacy_policy', 11 );
function bbloomer_add_registration_privacy_policy() {
woocommerce_form_field( 'privacy_policy_reg', array(
'type' => 'checkbox',
'class' => array('form-row privacy'),
'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
'required' => true,
'label' => 'I\'ve read and accept the <a href="/privacy-policy">Privacy Policy</a>',
));
}
// SHOW ERROR AFTER CLICKING SUBMIT BUTTON IF USER HAS NOT CHECKED CHECKBOX
add_filter( 'woocommerce_registration_errors', 'bbloomer_validate_privacy_registration', 10, 3 );
function bbloomer_validate_privacy_registration( $errors, $username, $email ) {
if ( ! is_checkout() ) {
if ( ! (int) isset( $_POST['privacy_policy_reg'] ) ) {
$errors->add( 'privacy_policy_reg_error', __( 'Privacy Policy consent is required!', 'woocommerce' ) );
}
}
return $errors;
}
UPDATE
- As per other question here: How can i make custom field value required ( compulsory ) in woocommerce product page when adding product I have already (unsuccessfully) tried:
'custom_attributes' => array( 'required' => 'required' ),
- As per suggestions, I have already tried:
required => "required" required => "required"