Автоматически применять купон только один раз для каждого пользователя на основе общей суммы, потраченной в WooCommerce - PullRequest
2 голосов
/ 24 апреля 2019

Я хотел бы применить купон автоматически на основе общей суммы потраченных клиентов.Этот купон должен быть применен только один раз клиентом.

Это то, что я пробовал до сих пор, но у меня пустой экран:

add_action( 'woocommerce_before_calculate_totals', 'loyalty_order_discount', 10, 1 );

function loyalty_order_discount( $order_id ) {
    global $woocommerce;

    $coupon = 'loyaltydiscount';
    $customer = new WC_Customer(get_current_user_id());
    $total_spent = 30;

    $order = wc_get_order( $order_id );

    foreach( $order->get_used_coupons( $customer ) as $coupon_name ){

        // Retrieving the coupon ID
        $coupon_post_obj = get_page_by_title($coupon_name, OBJECT, 'shop_coupon');
        $coupon_id = $coupon_post_obj->ID;

        $coupons_obj = new WC_Coupon($coupon_id);

        if( $coupons_obj == $coupon && $customer->get_total_spent() < $total_spent ){
            $woocommerce->cart->remove_coupon( $coupon );
        }
        elseif ( ! $coupons_obj == $coupon && $customer->get_total_spent() >= $total_spent){
            $woocommerce->cart->add_discount( $coupon );
        }
    }
}

Любая помощь приветствуется.

1 Ответ

0 голосов
/ 24 апреля 2019

Сначала необходимо установить для купона параметр «Лимит использования на пользователя» 1 (и сохранить) , например:

enter image description here

Теперь следующий пересмотренный код будет автоматически применять определенный купон только один раз, когда общая сумма расходов клиента достигла определенной суммы:

add_action( 'woocommerce_before_calculate_totals', 'enable_customer_loyalty_discount', 10, 1 );
function enable_customer_loyalty_discount( $cart ) {
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    //Your settings below
    $coupon_code = 'loyaltydiscount';
    $coupon_code = 'summer';
    $total_spent = 30;

    if( ! in_array( $coupon_code, $cart->get_applied_coupons() ) ) {
        $user_id  = get_current_user_id(); // User ID

        // Get the WC_Customer instance Object
        $customer = New WC_Customer( $user_id );
        $email    = $customer->get_billing_email(); // Billing email

        // If the user total spent has not reached the define amount, we exit
        if( $customer->get_total_spent() < $total_spent ) {
            return;
        }

        // Get the WC_Coupon instance Object
        $coupon = New WC_Coupon( $coupon_code );

        // If the coupon has already been used by the customer, we exit
        if( array_intersect( array($user_id, $email), $coupon->get_used_by() ) {
            return;
        }

        $cart->apply_coupon( $coupon_code );
    }
}

Код помещается в файл function.php вашей активной дочерней темы (или активной темы). Проверено и работает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...