如何获取WooCommerce客户过去一年已完成订单的消费总额?
修改后的代码实现
以下是调整后的代码,仅统计客户过去一年中「已完成」状态订单的消费总额:
add_shortcode('user_total_spent', 'get_user_total_spent'); function get_user_total_spent( $atts ) { extract( shortcode_atts( array( 'user_id' => get_current_user_id(), ), $atts, 'user_total_spent' ) ); if( $user_id > 0 ) { // 计算过去一年的起始时间戳并格式化 $one_year_ago = date('Y-m-d H:i:s', strtotime('-1 year')); // 查询用户过去一年的已完成订单 $orders = wc_get_orders(array( 'customer_id' => $user_id, 'status' => 'completed', 'date_created' => '>=' . $one_year_ago, 'limit' => -1, // 获取所有符合条件的订单 )); $total_spent = 0; // 累加符合条件的订单总金额 foreach ($orders as $order) { $total_spent += $order->get_total(); } // 原有等级判断逻辑保持不变 if( $total_spent > 600 && $total_spent < 1200 ){ $text = __( 'congrats you are now tier 1', 'woocommerce' ); }elseif( $total_spent > 1200 ){ $text = __( 'congrats you are now tier 2', 'woocommerce' ); }else{ $text = __( 'congrats you are now tier 3', 'woocommerce' ); } $total_spent_formatted = wc_price( $total_spent ); return "Total Amount Spent: ".$total_spent_formatted." ".$text; } }
关键修改说明
- 替换了原代码中
$customer->get_total_spent()全局统计方法,改用wc_get_orders精准查询指定条件的订单 - 通过
strtotime('-1 year')自动计算过去一年的起始日期,确保统计范围为最近12个月 - 订单查询新增
status => 'completed'条件,仅统计已完成的有效订单 - 遍历查询到的订单并累加总金额,得到符合要求的消费总额
内容的提问来源于stack exchange,提问作者Lgane
相关产品推荐
相关产品推荐

