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

如何获取WooCommerce中当前用户特定商品订单数据并判断购买状态

判断登录用户是否购买过特定商品并获取对应WooCommerce订单数据

不需要依赖WC_Order类的特定函数,直接通过wc_get_orders()获取用户订单,再遍历订单商品进行匹配即可实现需求,以下是完整的实现方案:

核心函数实现

function check_user_purchased_product_and_get_orders( $product_id ) {
    // 未登录直接返回未购买状态
    if ( ! is_user_logged_in() ) {
        return [
            'purchased' => false,
            'orders'    => []
        ];
    }

    $current_user_id = get_current_user_id();
    $matched_orders = [];

    // 获取用户的有效订单(可按需调整订单状态范围)
    $user_orders = wc_get_orders([
        'customer_id' => $current_user_id,
        'status'      => ['completed', 'processing'], // 仅统计已完成/处理中的订单
        'limit'       => -1, // 获取该用户所有符合条件的订单
    ]);

    foreach ( $user_orders as $order ) {
        // 遍历订单内的所有商品项
        foreach ( $order->get_items() as $item ) {
            if ( $item->get_product_id() === (int)$product_id ) {
                // 收集该订单的关键数据
                $matched_orders[] = [
                    'order_id'     => $order->get_id(),
                    'order_number' => $order->get_order_number(),
                    'created_at'   => $order->get_date_created()->format('Y-m-d H:i:s'),
                    'total'        => $order->get_total(),
                    'qty'          => $item->get_quantity(),
                    'item_subtotal'=> $item->get_subtotal()
                ];
                break; // 一个订单内只要匹配到目标商品,就停止遍历该订单的其他商品
            }
        }
    }

    return [
        'purchased' => !empty($matched_orders),
        'orders'    => $matched_orders
    ];
}

调用示例

// 替换为你要检查的目标商品ID
$target_product_id = 123;
$purchase_result = check_user_purchased_product_and_get_orders($target_product_id);

// 在页面上展示结果
if ( $purchase_result['purchased'] ) {
    echo '<h3>你已购买过该商品</h3>';
    echo '<ul>';
    foreach ( $purchase_result['orders'] as $order ) {
        echo '<li>订单号:' . $order['order_number'] . ' | 下单时间:' . $order['created_at'] . ' | 订单金额:' . wc_price($order['total']) . '</li>';
    }
    echo '</ul>';
} else {
    echo '<p>你尚未购买过该商品</p>';
}

关键说明

  • 使用wc_get_orders()是WooCommerce官方推荐的订单查询方式,相比直接操作数据库,能更好兼容不同版本的WooCommerce及后续更新
  • 可根据业务需求调整订单状态参数,比如添加'on-hold'(待支付)或移除状态限制获取所有订单
  • 订单数据可按需扩展,比如调用$order->get_status()获取订单状态、$order->get_billing_full_name()获取收货人名等,所有订单对象的方法均可在WooCommerce官方文档中查询到

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:40:24