I need to set a minimum lenght for username in a website that use WooCommerce.
In a “standard” WordPress installation (without WooCommerce, I mean) I could use a snippet like this one:
function my_registration_errors( $errors, $sanitized_user_login, $user_email )
{
if ( strlen( $sanitized_user_login ) < 5 ) {
$errors->add( 'username_too_short', __( '<strong>ERROR</strong>: Username must be at least 5 characters.' ) );
}
return $errors;
}
add_filter( 'registration_errors', 'my_registration_errors', 10, 3 );
Unfortunally it doesn’t work (I simply tested it with a fake registration) because WooCommerce has it’s own register form and hooks.
I’ve found a palliative solution that suggest to edit the form-login.php file adding a pattern attribute to the input fields <input pattern=".{3,}" required title="3 characters minimum">
, but I don’t want follow this procedure, I’d prefer to edit my functions.php instead.
I found a plugin called “Network Username Restrictions Override” but “it hasn’t been updated in over 2 years” and it refers to a network and I think it couldn’t fit my situation.
I’ve also tried to find another plugin in WordPress Plugin Directory but I found nothing.
Any suggestion?
1 Answer
Ok I found out the solution.
Because, as I said, WooCommerce has it’s own hooks, first of all I’ve searched for a WooCommerce hook about registration.
I discovered the existence of a hook very similiar to the one used by WordPress: woocommerce_registration_errors. Obviously it works in the same way.
Then I simply replaced the WordPress hook with the WooCommerce one. Here the final snippet you have to insert in your functions.php file:
add_filter( 'woocommerce_registration_errors', 'my_registration_errors', 10, 3 );
function my_registration_errors( $errors, $sanitized_user_login, $user_email )
{
if ( strlen( $sanitized_user_login ) < 5 ) {
$errors->add( 'username_too_short', __( '<strong>ERROR</strong>: Username must be at least 5 characters.' ) );
}
return $errors;
}