1

For example, if customers previous shopping record is more than 50k then he gets 50% discount.

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();
    }

}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399

2 Answers2

3

You could use wc_get_customer_total_spent() dedicated Woocommerce function, but this function take all orders paid status ( which are "processing" and "completed").

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:

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
1

$user_id = get_current_user_id();

$string = wc_get_customer_total_spent( $user_id );

echo $string;