You need to enable JavaScript to run this app. WooCommerce感谢页如何添加自定义meta_key「digits_phone」替代邮箱
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce感谢页如何添加自定义meta_key「digits_phone」替代邮箱

问题根因

之前同步后无输出的核心原因是混淆了订单级元数据和用户级元数据的存储逻辑:

  • 你原同步代码使用update_user_meta将手机号写入了登录用户的账户元数据,但$order->get_billing_phone()读取的是订单自身关联的计费字段元数据,二者存储位置完全独立,自然无法匹配到值。
  • 需求为直接读取digits_phone自定义字段值时,不需要依赖原有WooCommerce计费字段的同步逻辑,直接按照对应存储位置取值即可。
可直接替换的模板代码

可直接替换你原有订单概览区域<li>代码块的完整实现,兼顾登录用户、游客下单的兼容场景:

<?php
// 优先获取订单绑定的用户ID,兼容游客下单兜底
$target_user_id = $order->get_user_id();
if ( ! $target_user_id && is_user_logged_in() ) {
    $target_user_id = get_current_user_id();
}
// 读取digits_phone自定义字段值
$custom_phone = $target_user_id ? get_user_meta( $target_user_id, 'digits_phone', true ) : '';
// 仅在存在有效手机号时输出,避免空占位
if ( ! empty( $custom_phone ) ) :
?>
<li class="woocommerce-order-overview__phone phone">
    <?php esc_html_e( 'Phone:', 'woocommerce' ); ?>
    <strong><?php echo esc_html( $custom_phone ); ?></strong>
</li>
<?php endif; ?>
兼容多存储场景的优化

部分短信插件会同时将digits_phone写入订单级元数据(和用户级双存),可调整读取逻辑加一层兜底,避免历史订单取不到值:
将原代码中读取$custom_phone的行替换为:

// 优先读订单级自定义meta,无值时再读用户级meta
$custom_phone = $order->get_meta( 'digits_phone', true ) ?: ( $target_user_id ? get_user_meta( $target_user_id, 'digits_phone', true ) : '' );
原有同步方案的修正(可选)

如果仍希望沿用WooCommerce自带的get_billing_phone()方法输出,不需要手动在模板里写复杂的取值逻辑,只需将同步逻辑挂到订单创建钩子,把用户的digits_phone直接写入订单级的billing_phone元数据即可:

add_action( 'woocommerce_new_order', function( $order_id ) {
    $order = wc_get_order( $order_id );
    $user_id = $order->get_user_id();
    if ( ! $user_id ) return;
    $digits_phone = get_user_meta( $user_id, 'digits_phone', true );
    if ( $digits_phone ) {
        // 注意:写入订单元数据,而非用户元数据
        $order->update_meta_data( '_billing_phone', $digits_phone );
        $order->save();
    }
} );

注意:WooCommerce订单的billing_phone内部存储的meta key为带下划线前缀的_billing_phone,手动写入时需对应这个key格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.27 00:15:09