Применить автоматически купон на основе определенного количества товаров в Woocommerce - PullRequest
0 голосов
/ 17 сентября 2018

Я пытаюсь автоматически активировать купон, который будет применен в корзине, особенно если в корзине 4 товара.

Купон предварительно создан в бэк-энде сайта Woocommerce "tasterbox"

Я использую исправленную версию из этого кода ответа:
Добавить код купона WooCommerce автоматически на основе категорий продуктов

Вот моя версия кода:

add_action( 'woocommerce_before_calculate_totals', 'wc_auto_add_coupons', 10, 1 );
function wc_auto_add_coupons( $cart_object ) {

    // Coupon code
    $coupon = 'tasterbox';

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Initialising variables
    $is_match = false;
    $taster_item_count = 4;

    //  Iterating through each cart item
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // If cart items match 4
        if( $cart->cart_contents_count == $taster_item_count ){
            $is_match = true; // Set to true
            break; // stop the loop
        }
    }

    // If conditions are matched add the coupon discount
    if( $is_match && ! $cart_object->has_discount( $coupon )){
        // Apply the coupon code
        $cart_object->add_discount( $coupon );

        // Optionally display a message 
        wc_add_notice( __('TASTER BOX ADDED'), 'notice');
    } 
    // If conditions are not matched and coupon has been appied
    elseif( ! $has_category && $cart_object->has_discount( $coupon )){
        // Remove the coupon code
        $cart_object->remove_coupon( $coupon );

        // Optionally display a message 
        wc_add_notice( __('SORRY, TASTERBOX NOT VALID'), 'alert');
    }
}

Однако я не могу заставить его автоматически применять купон, когда в корзине 4 предмета. Это кажется чем-то простым, но я застрял.

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

1 Ответ

0 голосов
/ 17 сентября 2018

В вашем коде есть небольшие ошибки.Вместо этого попробуйте следующее:

add_action( 'woocommerce_before_calculate_totals', 'auto_add_coupon_based_on_cart_items_count', 25, 1 );
function auto_add_coupon_based_on_cart_items_count( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Setting and initialising variables
    $coupon = 'tasterbox'; // <===  Coupon code
    $item_count = 4; // <===  <===  Number of items
    $matched    = false;

    if( $cart->cart_contents_count >= $item_count ){
        $matched = true; // Set to true
    }

    // If conditions are matched add coupon is not applied
    if( $matched && ! $cart->has_discount( $coupon )){
        // Apply the coupon code
        $cart->add_discount( $coupon );

        // Optionally display a message
        wc_add_notice( __('TASTER BOX ADDED'), 'notice');
    }
    // If conditions are not matched and coupon has been appied
    elseif( ! $matched && $cart->has_discount( $coupon )){
        // Remove the coupon code
        $cart->remove_coupon( $coupon );

        // Optionally display a message
        wc_add_notice( __('SORRY, TASTERBOX NOT VALID'), 'error');
    }
}

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

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