Ваш реальный код тяжелый и устаревший ... Вместо этого попробуйте следующий, более легкий и эффективный способ, использующий свойство WC_Customer
is_paying_customer
:
add_action( 'woocommerce_before_calculate_totals', 'enable_customer_fidelity_discount', 10, 1 );
function enable_customer_fidelity_discount( $cart ) {
if ( ! ( is_cart() || is_checkout() ) )
return;
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// The discount coupon code below
$coupon_code = '10fidelity';
if( ! in_array( $coupon_code, $cart->get_applied_coupons() ) && WC()->customer->get_is_paying_customer() ) {
$cart->apply_coupon( $coupon_code );
} elseif( in_array( $coupon_code, $cart->get_applied_coupons() ) && ! WC()->customer->get_is_paying_customer() ) {
$cart->remove_coupon( $coupon_code );
}
}
Код входит в файл functions.phpваша активная детская тема (или активная тема).Протестировано и работает
Или с помощью этой улучшенной и легкой функции, которая проверяет, заказчик уже сделал заказ:
function has_bought( $user_id = 0 ) {
global $wpdb;
$customer_id = $user_id == 0 ? get_current_user_id() : $user_id;
$paid_order_statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() );
$results = $wpdb->get_col( "
SELECT p.ID FROM {$wpdb->prefix}posts AS p
INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $paid_order_statuses ) . "' )
AND p.post_type LIKE 'shop_order'
AND pm.meta_key = '_customer_user'
AND pm.meta_value = $customer_id
" );
// Count number of orders and return a boolean value depending if higher than 0
return count( $results ) > 0 ? true : false;
}
add_action( 'woocommerce_before_calculate_totals', 'enable_customer_fidelity_discount', 10, 1 );
function enable_customer_fidelity_discount( $cart ) {
if ( ! ( is_cart() || is_checkout() ) )
return;
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// The discount coupon code below
$coupon_code = 'summer';
if( ! in_array( $coupon_code, $cart->get_applied_coupons() ) && has_bought() ) {
$cart->apply_coupon( $coupon_code );
} elseif( in_array( $coupon_code, $cart->get_applied_coupons() ) && ! has_bought() ) {
$cart->remove_coupon( $coupon_code );
}
}
Код входит в файл functions.php вашей активной дочерней темы(или активная тема).Протестировано и работает.
Связано: