Существует несколько способов получить общую сумму покупок:
1) Вы можете заменить свою первую функцию, используя wc_get_customer_total_spent()
специальную функцию Woocommerce, но эта функция принимает статус всех оплаченных заказов (которые «обрабатываются» и «выполнены») .
2) Вы также можете использовать этот более легкий SQL-запрос, основанный на аналогичном исходном коде только для «завершенного» статуса заказа:
// Utililty function to get customer's total purchases sum
function get_customer_total_purchases_sum() {
$current_user_id = get_current_user_id(); // Current user ID
if( $current_user_id == 0 ) return 0; // we return zero if customer is not logged in
global $wpdb;
// return the SQL query (paid orders sum)
return $wpdb->get_var("SELECT SUM(pm.meta_value) FROM {$wpdb->prefix}postmeta as pm
INNER JOIN {$wpdb->prefix}postmeta as pm2 ON pm.post_id = pm2.post_id
INNER JOIN {$wpdb->prefix}posts as p ON pm.post_id = p.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 '$current_user_id'");
}
Этот код помещается в файл function.php вашей активной дочерней темы (или темы). Проверено и работает.
3) Или вы можете использовать свой собственный код функции вопроса (но он тяжелее) . Это зависит от вас.
Процентная скидка (2 способа) :
1) Отрицательный взнос:
Следующий код установит процентную скидку на основе общей суммы покупок клиента (используя мою функцию выше) :
// Percentage discount based on customer's total purchases sum
add_action('woocommerce_cart_calculate_fees', 'customer_purchases_total_sum_percentage_discount', 20, 1 );
function customer_purchases_total_sum_percentage_discount( $cart ){
// Only for logged in user
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
return;
## 1. Get the customer's purchases total sum (and save it in WC sessions to avoid multiple queries
// Check if it's saved in WC_Session
$purchases_sum = WC()->session->get( 'purchases_sum' );
// If not get it and save it
if( empty($purchases_sum) ){
// ==> HERE goes the function to get customer's purchases total sum
$purchases_sum = get_customer_total_purchases_sum();
// Save it in WC_Session
WC()->session->set('purchases_sum', $purchases_sum);
}
## 2. Set the discount percentage based on customer's total purchases sum
if( $purchases_sum >= 200 ){
$percent = 5; // 5%
}
if( isset($percent) && $percent > 0){
$discount = $cart->cart_contents_total * $percent / 100; // discount calculation
// Set the discount (For discounts (negative fee) the taxes as always included)
$cart->add_fee( __('Discount', 'woocommerce' ) . " (" . $percent . "%)", -$discount);
}
}
Этот код помещается в файл function.php вашей активной дочерней темы (или темы). Проверено и работает.
2) Автоматическое добавление кода купона (процентная скидка) :
Сначала необходимо установить новый код купона (процентная скидка 5%):
Затем вы будете использовать следующий код, который будет автоматически добавлять код купона на основе общей суммы покупок клиента (используя мою функцию выше) :
add_action( 'woocommerce_before_calculate_totals', 'customer_total_purchases_coupon_discount', 30, 1 );
function customer_total_purchases_coupon_discount( $cart ) {
// Only for logged in user
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// HERE define your coupon code (in lowercase)
$coupon_code = 'customersilver';
## 1. Get the customer's purchases total sum (and save it in WC sessions to avoid multiple queries
// Check if it's saved in WC_Session
$purchases_sum = WC()->session->get( 'purchases_sum' );
// If not get it and save it
if( empty($purchases_sum) ){
// ==> HERE goes the function to get customer's purchases total sum
$purchases_sum = get_customer_total_purchases_sum();
// Save it in WC_Session
WC()->session->set('purchases_sum', $purchases_sum);
}
## 2. Auto applying or removing a coupon code (percentage discount coupon)
// Apply the coupon if there is at least 2 units of "5 Reusable wet"
if ( ! $cart->has_discount( $coupon_code ) && $purchases_sum >= 200 ) {
$cart->add_discount( $coupon_code );
} elseif( $cart->has_discount( $coupon_code ) && $purchases_sum < 200 ) {
$cart->remove_coupon( $coupon_code );
}
}
Этот код помещается в файл function.php вашей активной дочерней темы (или темы). Проверено и работает.