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

如何将ACF用户路由字段添加至WooCommerce订单元数据?

解决WooCommerce用户自定义字段同步至订单详情的方案

核心思路

通过WooCommerce的钩子,在订单创建时自动关联用户(或匹配邮箱对应的用户)的自定义字段,将其写入订单元数据,这样Advanced Order Export Pro就能直接读取这些字段用于导出。


1. 代码实现(添加至主题functions.php)

这段代码会在订单创建时,把用户的routenumber和locations字段同步到订单详情中:

/**
 * 同步用户自定义字段到WooCommerce订单
 */
add_action('woocommerce_checkout_create_order', 'sync_user_custom_fields_to_order', 10, 2);
function sync_user_custom_fields_to_order($order, $checkout_data) {
    // 优先获取当前登录用户
    $user = wp_get_current_user();
    
    // 若用户未登录,尝试通过结账邮箱匹配已有用户
    if (!$user->ID && !empty($checkout_data['billing_email'])) {
        $user = get_user_by('email', $checkout_data['billing_email']);
    }
    
    // 仅当找到有效用户时同步字段
    if ($user && $user->ID) {
        // 获取用户元数据中的路由编号
        $routenumber = get_user_meta($user->ID, 'routenumber', true);
        if (!empty($routenumber)) {
            $order->update_meta_data('_user_routenumber', sanitize_text_field($routenumber));
        }
        
        // 获取用户元数据中的配送地点
        $locations = get_user_meta($user->ID, 'locations', true);
        if (!empty($locations)) {
            $order->update_meta_data('_user_locations', sanitize_text_field($locations));
        }
    }
}

代码说明:

  • 使用woocommerce_checkout_create_order钩子,在订单保存前触发,确保字段能被写入订单元数据
  • 支持两种场景:登录用户直接同步,未登录用户通过结账邮箱匹配已有用户
  • 用_user_routenumber和_user_locations作为订单元键(前缀下划线表示私有字段,不会在前端订单页面显示)
  • 用sanitize_text_field确保字段内容安全合规

2. 配置Advanced Order Export Pro导出字段

同步完成后,需要在导出插件中添加这些字段:

  • 打开Advanced Order Export Pro,创建或编辑你的导出模板
  • 点击「添加字段」→ 选择「自定义字段」
  • 分别添加元键_user_routenumber和_user_locations,设置对应的显示名称(如「路由编号」「配送地点」)
  • 保存模板后,即可按配送方式导出包含这些字段的订单数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 10:50:09