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

如何获取登录用户最新WooCommerce订单ID并用于Contact Form 7?

实现步骤

1. 传递用户最新订单ID到表单页面

有两种可靠方式将订单ID传递到Contact Form 7所在页面:

方式一:利用WooCommerce钩子存储订单ID到会话

在主题的functions.php或自定义插件中添加以下代码,用户完成订单后,将其订单ID存入WordPress会话,后续表单页面可直接读取:

add_action('woocommerce_thankyou', 'store_user_last_order_id_in_session');
function store_user_last_order_id_in_session($order_id) {
    if (is_user_logged_in()) {
        $order = wc_get_order($order_id);
        // 校验订单归属当前登录用户
        if ($order && $order->get_user_id() == get_current_user_id()) {
            if (!session_id()) {
                session_start();
            }
            $_SESSION['user_last_order_id'] = $order_id;
        }
    }
}

方式二:给感谢URL附加订单ID参数

如果仅针对特定产品生效,可通过钩子动态给产品的“感谢URL”添加订单ID参数:

add_filter('woocommerce_get_checkout_order_received_url', 'append_order_id_to_thankyou_url', 10, 2);
function append_order_id_to_thankyou_url($url, $order) {
    // 替换为目标产品ID,多个用数组如array(123, 456)
    $target_product_ids = array(123);
    $has_target_product = false;
    
    foreach ($order->get_items() as $item) {
        if (in_array($item->get_product_id(), $target_product_ids)) {
            $has_target_product = true;
            break;
        }
    }
    
    if ($has_target_product && is_user_logged_in()) {
        $url = add_query_arg('order_id', $order->get_id(), $url);
    }
    return $url;
}

2. 在Contact Form 7中添加隐藏字段

打开CF7表单编辑器,插入一个隐藏字段用于存储订单ID:

[hidden user_last_order_id default:get_user_last_order_id]

同时在functions.php中添加短代码函数,自动填充该隐藏字段的值:

add_shortcode('get_user_last_order_id', 'get_user_last_order_id_shortcode');
function get_user_last_order_id_shortcode() {
    $order_id = '';
    // 优先读取URL参数
    if (isset($_GET['order_id'])) {
        $order_id = sanitize_text_field($_GET['order_id']);
        $order = wc_get_order($order_id);
        // 二次校验订单归属
        if (!$order || $order->get_user_id() != get_current_user_id()) {
            $order_id = '';
        }
    } 
    // 其次读取会话存储的ID
    elseif (is_user_logged_in() && isset($_SESSION['user_last_order_id'])) {
        $order_id = sanitize_text_field($_SESSION['user_last_order_id']);
        $order = wc_get_order($order_id);
        if (!$order || $order->get_user_id() != get_current_user_id()) {
            $order_id = '';
        }
        // 可选:读取后清除会话,避免重复使用
        unset($_SESSION['user_last_order_id']);
    }
    return $order_id;
}

3. 在CF7邮件中插入订单ID

打开CF7的「邮件」设置标签,在发给管理员和用户的邮件内容中,插入以下标签即可显示订单ID:

用户最新订单ID:[user_last_order_id]

注意事项

  • 代码建议添加到自定义插件中,避免主题更新导致代码丢失。
  • 订单归属校验是必要的安全措施,防止用户恶意篡改订单ID参数。
  • 使用会话方式时,需确保服务器支持PHP会话功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 14:05:07