How to add HTML5 'required' attribute to woocommerce_form_field
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">
Примечание: в ловушке уже есть проверка PHP, но только после нажатия кнопки регистрации, тогда как проверка HTML5 работает мгновенно. Тем не менее, я хочу сохранить проверку проверки PHP на случай, если есть браузеры, которые не могут прочитать проверку HTML5.
Может ли кто-нибудь помочь мне, как нужно будет изменить код массива PHP, чтобы тег включал атрибут «required»?
Буду очень признателен за любую помощь!
Бест, Дэвид
// 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;
}
ОБНОВИТЬ
- В соответствии с другим вопросом здесь: Как я могу сделать значение настраиваемого поля обязательным (обязательным) на странице продукта woocommerce при добавлении продукта, который я уже (безуспешно) пробовал:
'custom_attributes' => array( 'required' => 'required' ),
- По предложениям я уже пробовал:
required => "required" required => "required"
Ответы
Если вы действительно хотите перейти <input..на, <input required..вы можете добавить woocommerce_form_field_checkboxперехватчик фильтра.
Дело в том, что там, где создается HTML-код
(Этот код был скопирован из wc-template-functions.phpстроки 2799)
<input type="' . esc_attr( $args['type'] ) . '" class="input-checkbox ' . esc_attr( implode( ' ', $args['input_class'] ) ) . '" name="' . esc_attr( $key ) . '" id="' . esc_attr( $args['id'] ) . '" value="1" ' . checked( $value, 1, false ) . ' /> ' . $args['label'] . $required . '</label>';
существует опция для добавления аргументов к существующему, $argsно не дополнительного HTMLкода к HTMLсамому себе
Поэтому, если вы добавите приведенный ниже код к существующему коду, у вас будет возможность настроить HTMLвывод из$field
- str_replace - заменяет все вхождения строки поиска строкой замены
function filter_woocommerce_form_field_checkbox( $field, $key, $args, $value ) { // Based on key if ( $key == 'privacy_policy_reg' ) {
$field = str_replace( '<input', '<input required', $field );
}
return $field;
}
add_filter( 'woocommerce_form_field_checkbox', 'filter_woocommerce_form_field_checkbox', 10, 4 );
Связанный: Как мне изменить HTML-структуру woocommerce_form_field?