Woocommerce如何将自定义meta_key digits_phone值写入订单billing_phone?
WooCommerce订单自动填充digits_phone到billing_phone字段问题排查
原有代码问题
- 赋值逻辑错误:你直接将
$data['billing_phone']赋值为['digits_phone']数组,没有从当前登录用户的元数据中读取digits_phone对应的值 - 缺少登录状态判断:未兼容游客下单场景,容易触发报错
- 没有对读取到的手机号做非空判断,极端情况下会把空值写入订单字段
修复后可用代码
// 自动将用户digits_phone元数据赋值给 WooCommerce 订单 billing_phone 字段 add_filter('woocommerce_checkout_posted_data', 'dg_manipulate_checkout_posted_data'); function dg_manipulate_checkout_posted_data ($data) { // 仅在用户登录时读取用户元数据 if (is_user_logged_in()) { $user_id = get_current_user_id(); $digits_phone = get_user_meta($user_id, 'digits_phone', true); // 读取到有效手机号再赋值 if (!empty($digits_phone)) { $data['billing_phone'] = $digits_phone; } } return $data; }
额外说明
如果希望即使用户在 checkout 页面手动修改了手机号,也强制覆盖为digits_phone的值,可以换用woocommerce_checkout_create_order钩子,在订单生成的最后节点强制写入字段,优先级更高。
内容的提问来源于stack exchange,提问作者Erfan
相关产品推荐
相关产品推荐

