I have added some new fields to my woocommerce registration form, but i can’t validate these new fields.
There’s my new fields
add_action('register_form','myplugin_register_form');
function myplugin_register_form (){
$first_name = ( isset( $_POST['first_name'] ) ) ? $_POST['first_name']: '';
$last_name = ( isset( $_POST['last_name'] ) ) ? $_POST['last_name']: '';
?>
<div class="row">
<div class="col-md-4">
<label for="first_name">Prénom <span class="required">*</span></label>
<input type="text" class="input-text" name="first_name" id="first_name" value="<?php if ( ! empty( $_POST['first_name'] ) ) echo esc_attr( $_POST['first_name'] ); ?>" />
</div>
<div class="col-md-4">
<label for="last_name">Nom <span class="required">*</span></label>
<input type="text" class="input-text" name="last_name" id="last_name" value="<?php if ( ! empty( $_POST['last_name'] ) ) echo esc_attr( $_POST['last_name'] ); ?>" />
</div>
</div>
<?php
}
And this is my filter for the validation according to the wordpress codex https://codex.wordpress.org/Customizing_the_Registration_Form
function myplugin_registration_errors ($errors, $sanitized_user_login, $user_email) {
if ( empty( $_POST['first_name'] ) )
$errors->add( 'first_name_error', __('<strong>ERROR</strong>: You must include a first name.','mydomain') );
return $errors;
}
When i submit my form, without the field $_POST[‘first_name’] it passe without errors.
What’s the best way to do it?
Thank you for your help
Please write this code in theme’s/child theme’s functions.php
If you look in
woocommerce-fundtions.php
it check for$woocommerce->error
and then proceed. So, instead adding errors to wordpress-count() == 0
$errors
I would add errors to Woocommerce like$woocommerce->add_error( $reg_errors->get_error_message() )
So the code would be