You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为WooCommerce重置密码表单添加自定义字段并保存数据

为WooCommerce重置密码表单添加自定义姓名字段

要在WooCommerce的重置密码表单(用户邮箱验证后设置密码的环节)添加名字和姓氏字段,需要完成三个核心步骤:添加字段到表单、验证字段必填性、保存字段数据到用户账户。以下是具体实现代码:

1. 在重置密码表单中插入自定义字段

利用woocommerce_resetpassword_form钩子,将姓名字段插入到表单中,保持和WooCommerce原生表单一致的样式结构:

add_action( 'woocommerce_resetpassword_form', 'add_first_last_name_to_reset_password_form' );
function add_first_last_name_to_reset_password_form() {
    ?>
    <p class="woocommerce-form-row woocommerce-form-row--first form-row form-row-first">
        <label for="account_first_name"><?php esc_html_e( '名字', 'woocommerce' ); ?>&nbsp;<span class="required">*</span></label>
        <input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="account_first_name" id="account_first_name" autocomplete="given-name" value="<?php echo ! empty( $_POST['account_first_name'] ) ? esc_attr( $_POST['account_first_name'] ) : ''; ?>" />
    </p>
    <p class="woocommerce-form-row woocommerce-form-row--last form-row form-row-last">
        <label for="account_last_name"><?php esc_html_e( '姓氏', 'woocommerce' ); ?>&nbsp;<span class="required">*</span></label>
        <input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="account_last_name" id="account_last_name" autocomplete="family-name" value="<?php echo ! empty( $_POST['account_last_name'] ) ? esc_attr( $_POST['account_last_name'] ) : ''; ?>" />
    </p>
    <?php
}

2. 验证字段的必填性

通过woocommerce_resetpassword_validation钩子,检查姓名字段是否为空,若为空则返回错误提示:

add_action( 'woocommerce_resetpassword_validation', 'validate_first_last_name_reset_password_fields', 10, 2 );
function validate_first_last_name_reset_password_fields( $errors, $user ) {
    if ( empty( $_POST['account_first_name'] ) ) {
        $errors->add( 'first_name_error', esc_html__( '请填写您的名字。', 'woocommerce' ) );
    }
    if ( empty( $_POST['account_last_name'] ) ) {
        $errors->add( 'last_name_error', esc_html__( '请填写您的姓氏。', 'woocommerce' ) );
    }
    return $errors;
}

3. 保存字段数据到用户账户

在用户成功重置密码后,通过woocommerce_resetpassword_success钩子,将填写的姓名保存到用户的账户元数据中:

add_action( 'woocommerce_resetpassword_success', 'save_first_last_name_from_reset_password_form' );
function save_first_last_name_from_reset_password_form( $user ) {
    if ( ! empty( $_POST['account_first_name'] ) ) {
        update_user_meta( $user->ID, 'first_name', sanitize_text_field( $_POST['account_first_name'] ) );
    }
    if ( ! empty( $_POST['account_last_name'] ) ) {
        update_user_meta( $user->ID, 'last_name', sanitize_text_field( $_POST['account_last_name'] ) );
    }
}

代码使用说明

将上述三段代码添加到当前WordPress主题的functions.php文件中,或者创建一个自定义插件来存放代码(推荐后者,避免主题更新导致代码丢失)。

内容的提问来源于stack exchange,提问作者user2067621

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 18:42:22