[英]Get customer's total paid orders sum in Woocommerce 3
For example, if customers previous shopping record is more than 50k then he gets 50% discount. 例如,如果客户以前的购物记录超过5万,那么他将获得50%的折扣。
Here is my code, which is used to retrieve the customer's current order price, but I want to retrieve the total order price: 这是我的代码,用于检索客户当前的订单价格,但我想检索总订单价格:
add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );
function apply_matched_coupons() {
global $woocommerce;
$coupon_code = '10percent'; // your coupon code here
if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;
if ( $woocommerce->cart->cart_contents_total >= 500 ) {
$woocommerce->cart->add_discount( $coupon_code );
$woocommerce->show_messages();
}
}
You could use wc_get_customer_total_spent()
dedicated Woocommerce function, but this function take all orders paid status ( which are "processing" and "completed") . 您可以使用wc_get_customer_total_spent()
专用的Woocommerce函数,但是此函数采用所有已付款订单状态(“正在处理”和“已完成”) 。
To get the sum of all customer purchases (for "completed" orders status only) you can use this simple and lighter SQL based on wc_get_customer_total_spent()
similar source code that will do the trick: 要获得所有客户购买的总和(仅针对“已完成”订单状态),您可以使用基于wc_get_customer_total_spent()
类似源代码的此简单且轻松的SQL:
global $wpdb;
$user_id = get_current_user_id(); // Current user ID
$user_purchases_total_sum = $wpdb->get_var( "
SELECT SUM(pm.meta_value) FROM {$wpdb->prefix}postmeta as pm
INNER JOIN {$wpdb->prefix}posts as p ON pm.post_id = p.ID
INNER JOIN {$wpdb->prefix}postmeta as pm2 ON pm.post_id = pm2.post_id
WHERE p.post_status LIKE 'wc-completed' AND p.post_type LIKE 'shop_order'
AND pm.meta_key LIKE '_order_total' AND pm2.meta_key LIKE '_customer_user'
AND pm2.meta_value LIKE $user_id
" );
Tested and works. 经过测试和工作。
$user_id = get_current_user_id(); $ user_id = get_current_user_id();
$string = wc_get_customer_total_spent( $user_id ); $ string = wc_get_customer_total_spent($ user_id);
echo $string; echo $ string;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.