WooCommerce: Add Password Confirmation Field to Registration Form

Users can register on both the account registration page and during checkout (if enabled).  This code will add a field for the user to confirm the password that they entered in the primary password field.

// Validate password match on the registration page
function myprefix_registration_errors_validation($reg_errors, $sanitized_user_login, $user_email) {
  global $woocommerce;
  extract( $_POST );
  if ( strcmp( $password, $password2 ) !== 0 ) {
    return new WP_Error( 'registration-error', __( 'Passwords do not match.', 'woocommerce' ) );
  }
  return $reg_errors;
}
add_filter('woocommerce_registration_errors', 'myprefix_registration_errors_validation', 10,3);

// Add a confirm password fields match on the registration page
function myprefix_wc_register_form_password_repeat() {
  ?>
  <p class="form-row form-row-wide">
    <label for="reg_password2"><?php _e( 'Verify Password', 'woocommerce' ); ?> <span class="required">*</span></label>
    <input type="password" class="input-text" name="password2" id="reg_password2" value="<?php if ( ! empty( $_POST['password2'] ) ) echo esc_attr( $_POST['password2'] ); ?>" />
  </p>
  <?php
}
add_action( 'woocommerce_register_form', 'myprefix_wc_register_form_password_repeat', 1 );

// Validate confirm password field match to the checkout page
function myprefix_woocommerce_confirm_password_validation( $posted ) {
  $checkout = WC()->checkout;
  if ( ! is_user_logged_in() && ( $checkout->must_create_account || ! empty( $posted['createaccount'] ) ) ) {
    if ( strcmp( $posted['account_password'], $posted['account_confirm_password'] ) !== 0 ) {
      wc_add_notice( __( 'Passwords do not match.', 'woocommerce' ), 'error' ); 
    }
  }
}
add_action( 'woocommerce_after_checkout_validation', 'myprefix_woocommerce_confirm_password_validation', 10, 2 );

// Add a confirm password field to the checkout page
function myprefix_woocommerce_confirm_password_checkout( $checkout ) {
  if ( get_option( 'woocommerce_registration_generate_password' ) == 'no' ) {
    $fields = $checkout->get_checkout_fields();
    $fields['account']['account_confirm_password'] = array(
      'type'              => 'password',
      'label'             => __( 'Confirm password', 'woocommerce' ),
      'required'          => true,
      'placeholder'       => _x( 'Confirm Password', 'placeholder', 'woocommerce' )
    );
    $checkout->__set( 'checkout_fields', $fields );
  }
}
add_action( 'woocommerce_checkout_init', 'myprefix_woocommerce_confirm_password_checkout', 10, 1 );