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

如何在WooCommerce中更新订单电话号码元数据并移除斜杠?

解决WooCommerce订单电话元数据更新问题

你的代码之所以会新建自定义字段,核心原因是用了错误的元数据键——WooCommerce默认的账单电话元数据键是_billing_phone(带下划线),而你写的phone是自定义键,自然会生成新字段。另外直接依赖$_POST数据不够稳妥,建议通过订单对象操作更规范。

方案1:修改原有钩子代码(适配已创建的订单)

如果要在订单创建后修正电话,可调整如下:

add_action( 'woocommerce_new_order', 'update_order_meta_phone' );
function update_order_meta_phone( $order_id ) {
    $order = wc_get_order( $order_id );   
    if ( $order && ! empty( $order->get_billing_phone() ) ) {
        // 移除电话号码中的"/"符号
        $cleaned_phone = str_replace( '/', '', $order->get_billing_phone() );
        // 更新默认账单电话元数据
        $order->update_meta_data( '_billing_phone', sanitize_text_field( $cleaned_phone ) );
        $order->save();
    }
}

方案2:推荐使用订单创建前的钩子(更高效)

用woocommerce_checkout_create_order钩子在订单正式创建前就处理电话,避免事后修改,同时兼容前台和后台创建订单的场景:

add_action( 'woocommerce_checkout_create_order', 'clean_billing_phone_before_order_create', 10, 2 );
function clean_billing_phone_before_order_create( $order, $data ) {
    if ( ! empty( $data['billing']['phone'] ) ) {
        $cleaned_phone = str_replace( '/', '', $data['billing']['phone'] );
        $order->set_billing_phone( sanitize_text_field( $cleaned_phone ) );
    }
}

关键说明

  • 改用_billing_phone键,才能覆盖WooCommerce默认的账单电话字段,而不是新建自定义字段。
  • 使用订单对象的get_billing_phone()、set_billing_phone()方法,比直接操作post_meta更符合WooCommerce的开发规范,也能避免数据异常。

内容的提问来源于stack exchange,提问作者Jr.Joseph

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:05:21