如何在WooCommerce中计算用户消费总额时排除手动部分退款
解决WooCommerce用户周期总消费扣除部分退款的问题
原代码仅统计了wc_orders表中的订单初始总金额,但WooCommerce的部分退款数据单独存在wc_refunds表中,因此需要关联两张表,计算订单总额减去对应退款总额后的实际消费金额。
修改后的完整代码如下:
// 工具函数:计算用户特定周期内特定状态订单的实际总消费(扣除部分退款) function get_orders_sum_amount_for( $user_id, $period = '1 year', $status = 'completed' ) { global $wpdb; return $wpdb->get_var( $wpdb->prepare( " SELECT SUM( o.total_amount - COALESCE( SUM(r.amount), 0 ) ) AS actual_total FROM {$wpdb->prefix}wc_orders o LEFT JOIN {$wpdb->prefix}wc_refunds r ON o.id = r.parent_id WHERE o.status = %s AND o.customer_id = %d AND o.date_created_gmt >= %s GROUP BY o.id ", 'wc-'.$status, $user_id, date('Y-m-d H:i:s', strtotime('-'.$period) ) ) ); } add_shortcode('user_year_total_spent', 'get_user_year_total_spent'); function get_user_year_total_spent( $atts ) { extract( shortcode_atts( array( 'user_id' => get_current_user_id(), ), $atts, 'user_year_total_spent' ) ); if( ! $user_id ) return; $total_spent = get_orders_sum_amount_for( $user_id ); // 获取扣除退款后的实际总消费 // 处理无订单时的空值情况 $total_spent = $total_spent ?: 0; if( $total_spent >= 1200 ) { $text = __('Congrats you are now tier 3.', 'woocommerce'); } elseif ( $total_spent >= 600 ) { $text = __('Congrats you are now tier 2.', 'woocommerce'); } else { $text = __('Congrats you are now tier 1.', 'woocommerce'); } return sprintf(__('Total Amount Spent: %s. %s', 'woocommerce'), wc_price($total_spent), $text); } // 短码使用:[user_year_total_spent]
关键修改说明:
- 用
LEFT JOIN关联wc_refunds表,通过parent_id绑定退款对应的订单ID COALESCE(SUM(r.amount), 0)确保无退款的订单不会被减去空值,默认用0替代- 按订单ID分组后,计算每个订单的实际金额(订单总额 - 退款总额),再求和得到用户真实消费
- 新增空值处理逻辑,避免用户无订单时出现显示异常
内容的提问来源于stack exchange,提问作者Lgane
相关产品推荐
相关产品推荐

