Blog

WooCommerce Custom Password Strength

Haven’t you been wanting to do this? To choose your own password strength for WC? Haven’t you? Well, here’s a quick way to copy paste this into your `functions.php` file or a more “correct” configuration file/model inside infinitely recursing folders for proper organization of your code.

// Customize required password strength START

// Main function that handles the password strength check
function prefix_check_password( $password, &$errors ) {
 // If password is empty and it's the checkout page then it's okay, it means
 // the user is anonymous and doesn't want to create an account
 if ( is_checkout() && $password == '' ) return

 /*** Your password strength checks go here ***/

 /* These are the ones I used: */
 // Password must be at least 7 characters in length
 if ( strlen( $password ) < 7 )
 $errors->add( "length", "Password must be at least 7 characters in length" );
 // Password should have upper and lowercase characters
 if ( strtolower( $password ) == $password || strtoupper( $password ) == $password )
 $errors->add( "upper_lower", "Password must have uppercase and lowercase characters" );
 // Password must have numbers
 if ( preg_match('%\d%', $password ) == 0 )
 $errors->add( "number", "Password must contain number characters" );
}

// MyAccount
add_action( 'woocommerce_save_account_details_errors', function( $errors, $user ) {
 if ( !property_exists( $user, 'user_pass') ) return;
 prefix_check_password( $user->user_pass, $errors );
}, 10, 2 );

// New Account
add_action( 'woocommerce_process_registration_errors', function( $validation_error, $username, $password, $email ) {
 prefix_check_password( $password, $validation_error );
 return $validation_error;
}, 10, 4 );

// Checkout New Account
add_action( 'woocommerce_before_checkout_process', function() {
 if ( isset( $_POST['account_password'] ) ) {
 $password = $_POST['account_password'];
 }
 $errors = new WP_Error;
 prefix_check_password( $password, $errors );
 // This one requires the exception to be thrown
 if ( $errors->get_error_code() ) {
 $text = "";
 foreach ($errors->errors as $error) {
 $text .= $error[0] . "<br>";
 }
 throw new Exception( $text, 1 );
 }
}, 10, 1 );
// Customize required password strength END

I’d say more, but, sometimes, sometimes the code just speaks for itself. Orrr maybe this is too simple to come up with any interesting/useful comments… You be the judge.

Leave a Comment