使用获取客户 1 年内在 WooCommerce 中的总支出。
// Utility function: Get customer orders total amount from specific status on a period
function get_orders_sum_amount_for( $user_id, $period = '1 year', $status = 'completed' ) {
global $wpdb;
return $wpdb->get_var( $wpdb->prepare( "
SELECT SUM(total_amount)
FROM {$wpdb->prefix}wc_orders
WHERE status = %s
AND customer_id = %d
AND date_created_gmt >= %s
", '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 ); // Get total spent amount
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]
echo do_shortcode('[user_year_total_spent]');
它接收所有已完成的用户订单在一定时间内的总支出。
但我面临这样一个事实:如果订单被部分退回,那么总支出不会因部分退款而减少。
示例: 订购 3 件 T 恤 * 10 欧盟。 总花费 30 欧元。配送费用不包含在总支出中。 此外,买家在该订单中退回了 1 件 T 恤 * 10 EU。管理员手动发放了部分退款。 订单状态“已完成”,2 件 T 恤 * 20 欧元。但总花费仍然是 30 欧元。
如何从总支出中排除部分手动退款?
function get_orders_sum_amount_for( $user_id, $period = '1 year', $status = 'completed' ) {
global $wpdb;
$date = date('Y-m-d H:i:s', strtotime('-'.$period) );
$status = 'wc-'.$status;
$total_orders = (float) $wpdb->get_var( $wpdb->prepare( "
SELECT SUM(total_amount) FROM {$wpdb->prefix}wc_orders
WHERE status = %s AND customer_id = %d AND date_created_gmt >= %s
", $status, $user_id, $date ) );
$total_refunds = (float) $wpdb->get_var( $wpdb->prepare( "
SELECT SUM(r.total_amount)
FROM {$wpdb->prefix}wc_orders r
LEFT JOIN {$wpdb->prefix}wc_orders o ON r.parent_order_id = o.id
WHERE r.type = 'shop_order_refund' AND r.status = %s
AND o.customer_id = %d AND o.date_created_gmt >= %s
", $status, $user_id, $date) );
return $total_orders + $total_refunds;
}
代码位于活动子主题(或活动主题)的functions.php 文件中。已测试并有效。