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

Woocommerce单商品页显示当前用户该商品累计购买次数

嘿,这个需求其实很好实现,咱们一步步来搞定它~

在WooCommerce单个商品页显示当前用户累计购买次数

首先得明确核心逻辑:只给登录用户展示他自己对当前商品的累计购买量,排除未登录用户,也不统计总销量。下面是完整的解决方案:

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

建议用子主题的functions.php或者自定义代码插件(比如Code Snippets)来添加,避免主题更新丢失代码:

// 核心:计算当前用户对指定商品的累计购买次数
function get_current_user_product_purchase_count( $product_id ) {
    // 未登录用户直接返回0,不显示内容
    if ( ! is_user_logged_in() ) {
        return 0;
    }

    $current_user_id = get_current_user_id();
    
    // 查询该用户所有已完成的订单(只统计已完成的,避免未支付/取消订单干扰)
    $orders = wc_get_orders( array(
        'customer_id' => $current_user_id,
        'status'      => array( 'completed' ),
        'limit'       => -1, // 获取所有符合条件的订单
    ) );

    $purchase_count = 0;

    // 遍历订单,累加目标商品的购买数量
    foreach ( $orders as $order ) {
        foreach ( $order->get_items() as $item ) {
            if ( $item->get_product_id() == $product_id ) {
                $purchase_count += $item->get_quantity();
            }
        }
    }

    return $purchase_count;
}

// 在单个商品页面输出购买次数
function display_current_user_purchase_count() {
    // 只在单个商品页面执行
    if ( ! is_product() ) {
        return;
    }

    global $product;
    $product_id = $product->get_id();
    $count = get_current_user_product_purchase_count( $product_id );

    // 自定义显示内容,可根据需求调整
    if ( $count > 0 ) {
        echo '<div class="user-purchase-count">您已购买该商品 <strong>' . esc_html( $count ) . '</strong> 次</div>';
    } else {
        // 可选:用户没买过的提示,不需要可以删掉这部分
        echo '<div class="user-purchase-count">您还未购买过该商品</div>';
    }
}
// 挂钩到商品页面的合适位置,优先级15表示在价格之后、加购按钮之前显示
add_action( 'woocommerce_single_product_summary', 'display_current_user_purchase_count', 15 );

细节说明

  1. 统计逻辑:只筛选已完成的订单,确保数据准确,不会把未支付、取消的订单算进去
  2. 显示位置:通过woocommerce_single_product_summary钩子控制,调整优先级数字可以改变位置:
    • 优先级10:在商品标题之后显示
    • 优先级20:在加购按钮之后显示
  3. 样式美化(可选):如果想让显示更美观,在主题style.css里加一段CSS:
.user-purchase-count {
    margin: 15px 0;
    padding: 10px;
    background-color: #f5f5f5;
    border-radius: 4px;
    font-size: 16px;
}

这样设置后,John登录看钢笔商品页就会显示他的2次购买记录,Jack登录则显示5次,完全符合你的需求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:58:51