- 添加自定义字段:代码在注册表单中添加了密码和确认密码字段。
- 验证逻辑:
- 验证密码和确认密码字段是否为空。
- 检查密码和确认密码是否匹配。
- 保存密码:通过
wp_set_password
函数将用户输入的密码设置为 WordPress 用户密码。 - 禁用随机密码邮件:通过
send_password_change_email
过滤器,禁用 WooCommerce 默认发送密码邮件的行为。
用户现在可以在注册时设置自己的密码,并且不会收到自动生成的密码邮件。这种方法符合 WooCommerce 的注册逻辑,同时避免了用户体验问题。
// 在注册页面添加密码和确认密码字段
function woocom_extra_register_fields() {
?>
<p class="form-row form-row-wide mb-4">
<label for="reg_password" class="text-uppercase"><?php _e('Password', 'woocommerce'); ?><span class="required">*</span></label>
<input type="password" class="input-text form-control" name="password" id="reg_password" value="<?php if ( ! empty( $_POST['password'] ) ) esc_attr_e( $_POST['password'] ); ?>" placeholder="Password" />
</p>
<p class="form-row form-row-wide">
<label for="reg_confirm_password" class="text-uppercase"><?php _e('Confirm Password', 'woocommerce'); ?><span class="required">*</span></label>
<input type="password" class="input-text form-control" name="confirm_password" id="reg_confirm_password" value="<?php if ( ! empty( $_POST['confirm_password'] ) ) esc_attr_e( $_POST['confirm_password'] ); ?>" placeholder="Confirm Password" />
</p>
<?php
}
add_action('woocommerce_register_form', 'woocom_extra_register_fields');
// 验证输入的密码字段
function woocom_validate_extra_register_fields( $username, $email, $validation_errors ) {
if ( isset( $_POST['password'] ) && empty( $_POST['password'] ) ) {
$validation_errors->add('password_error', __('Password is required!', 'woocommerce'));
}
if ( isset( $_POST['confirm_password'] ) && empty( $_POST['confirm_password'] ) ) {
$validation_errors->add('confirm_password_error', __('Confirm password is required!', 'woocommerce'));
}
if ( ! empty( $_POST['password'] ) && ! empty( $_POST['confirm_password'] ) && $_POST['password'] !== $_POST['confirm_password'] ) {
$validation_errors->add('password_mismatch_error', __('Passwords do not match!', 'woocommerce'));
}
return $validation_errors;
}
add_action('woocommerce_register_post', 'woocom_validate_extra_register_fields', 10, 3);
// 保存用户输入的密码
function woocom_save_extra_register_fields($customer_id) {
if ( isset( $_POST['password'] ) && ! empty( $_POST['password'] ) ) {
wp_set_password( sanitize_text_field( $_POST['password'] ), $customer_id );
}
}
add_action('woocommerce_created_customer', 'woocom_save_extra_register_fields');
// 禁用 WooCommerce 默认生成随机密码并发送邮件
add_filter('send_password_change_email', '__return_false');
要隐藏 WooCommerce 在注册页面上显示的提示 "设置新密码的链接将发送到您的电子邮件地址",可以通过以下方法:
add_filter( 'woocommerce_registration_generate_password', '__return_false' );
add_filter( 'gettext', 'custom_hide_password_email_text', 20, 3 );
function custom_hide_password_email_text( $translated_text, $text, $domain ) {
if ( 'woocommerce' === $domain && 'A link to set a new password will be sent to your email address.' === $text ) {
$translated_text = ''; // 隐藏提示内容
}
return $translated_text;
}
还没有评论呢,快来抢沙发~