默认情况下,WordPress 用户在注册时仅要求填写用户名和电子邮件,密码将由发送的密码重置链接进行设置。文本分享一段最新 WordPress 注册直接输入密码代码,用户注册时自动生成随机密码,并检测密码强度,让用户自己选择使用随机密码或者直接输入密码。
将代码添加到前主题函数模板functions.php
中:
// 添加输入密码表单
add_action( 'register_form', function () { ?>
<div class="user-pass1-wrap">
<p>
<label for="pass1"><?php _e( 'Password' ); ?></label>
</p>
<div class="wp-pwd">
<input type="password" data-reveal="1" data-pw="<?php echo esc_attr( wp_generate_password( 16 ) ); ?>" name="pass1" id="pass1" class="input password-input" size="24" value="" autocomplete="off" aria-describedby="pass-strength-result" />
<button type="button" class="button button-secondary wp-hide-pw hide-if-no-js" data-toggle="0" aria-label="<?php esc_attr_e( 'Hide password' ); ?>">
<span class="dashicons dashicons-hidden" aria-hidden="true"></span>
</button>
<div id="pass-strength-result" class="hide-if-no-js" aria-live="polite"><?php _e( 'Strength indicator' ); ?></div>
</div>
<div class="pw-weak">
<input type="checkbox" name="pw_weak" id="pw-weak" class="pw-checkbox" />
<label for="pw-weak"><?php _e( 'Confirm use of weak password' ); ?></label>
</div>
</div>
<p class="user-pass2-wrap">
<label for="pass2"><?php _e( 'Confirm new password' ); ?></label>
<input type="password" name="pass2" id="pass2" class="input" size="20" value="" autocomplete="off" />
</p>
<p class="description indicator-hint"><?php echo wp_get_password_hint(); ?></p>
<?php
});
// 加载验证JS
add_action( 'login_enqueue_scripts', function () {
if ( is_on_registration_page() && !wp_script_is( 'user-profile' ) ) {
wp_enqueue_script('user-profile');
}
});
// 验证
function is_on_registration_page() {
return $GLOBALS['pagenow'] == 'wp-login.php' && isset( $_REQUEST['action'] ) && $_REQUEST['action'] == 'register';
}
// 错误提示
add_filter( 'registration_errors', function ( $errors ) {
if ( empty( $_POST['pass1'] ) ) {
$errors->add( 'password-required', '<strong>Error</strong>: Please enter a password.' );
}
if ( empty( $_POST['pass2'] ) ) {
$errors->add( 'password-required', '<strong>Error</strong>: Please enter a password confirmation.' );
}
return $errors;
});
// 生成随机密码
add_filter( 'random_password', function ( $password ) {
if ( is_on_registration_page() && ! empty( $_POST['pass1'] ) ) {
$password = $_POST['pass1'];
}
return $password;
});
// 自定义邮件内容
add_filter( 'wp_new_user_notification_email', function ( $wp_new_user_notification_email, $user ) {
$message = sprintf( __( 'Username: %s' ), $user->user_login ) . "\r\n\r\n";
$message .= __( 'Password: As entered during your registration' ) . "\r\n\r\n";
$message .= wp_login_url() . "\r\n";
$wp_new_user_notification_email['message'] = $message;
return $wp_new_user_notification_email;
}, 10, 2 );
效果如图:
密码强度不够,需要勾选“确认使用弱密码”,否则注册按钮呈灰色不可点击。
如果想在WP默认注册页面和前端注册表单中同时应用这个检测功能,需要再加上:
// 在前端加载验证JS
add_action( 'wp_footer', function () {
if ( !wp_script_is( 'user-profile' ) ) {
wp_enqueue_script('user-profile');
}
});
并在按钮HTML代码中添加:id="wp-submit"
评论前必须登录!
注册