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

如何在WooCommerce edit-account模板表单中修改已添加的手机号字段值

你遇到的问题来自两个核心疏漏:

  1. 账户编辑页的手机号字段默认仅读取POST提交的临时值,没有加载用户已存储的billing_phone元数据,因此无法展示已保存的旧值
  2. 你仅实现了注册场景下的字段保存逻辑,没有绑定WooCommerce账户编辑场景的保存钩子,因此修改后的值无法写入数据库

步骤1:修改账户编辑模板的手机号字段

把你form-edit-account.php里的手机号字段代码替换为以下内容,让它默认显示已存储的手机号,提交报错时保留刚输入的临时值:

<div class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide form-group">       
    <input type="text" name="billing_phone" id="reg_billing_phone" placeholder="<?php _e( 'Phone', 'woocommerce' ); ?>" 
    value="<?php echo isset( $_POST['billing_phone'] ) ? esc_attr( $_POST['billing_phone'] ) : esc_attr( get_user_meta( $user->ID, 'billing_phone', true ) ); ?>" 
    class="woocommerce-Input woocommerce-Input--text input-text form-control" size="25" />
</div>

步骤2:添加账户编辑页的字段验证逻辑

在你主题的functions.php(或存放注册逻辑的自定义代码文件)中添加以下代码,用于编辑账户时验证手机号必填:

// 验证账户编辑页的手机号字段
function wooc_validate_edit_account_phone( $errors, $user ) {
    if ( isset( $_POST['billing_phone'] ) && empty( $_POST['billing_phone'] ) ) {
        $errors->add( 'billing_phone_error', __( '<strong>错误</strong>: 手机号为必填项', 'woocommerce' ) );
    }
    return $errors;
}
add_action( 'woocommerce_save_account_details_errors', 'wooc_validate_edit_account_phone', 10, 2 );

步骤3:添加账户编辑页的手机号保存逻辑

同样在functions.php中添加以下代码,绑定编辑账户的保存钩子,将修改后的手机号写入用户元数据:

// 保存账户编辑页的手机号字段
function wooc_save_edit_account_phone( $user_id ) {
    if ( isset( $_POST['billing_phone'] ) ) {
        // 同时更新WooCommerce账单手机号和通用用户手机号字段,方便其他场景调用
        update_user_meta( $user_id, 'billing_phone', sanitize_text_field( $_POST['billing_phone'] ) );
        update_user_meta( $user_id, 'phone', sanitize_text_field( $_POST['billing_phone'] ) );
    }
}
add_action( 'woocommerce_save_account_details', 'wooc_save_edit_account_phone' );

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:06:03