Бесплатная раздача товара для указанной c корзины в WooCommerce - PullRequest
0 голосов
/ 10 июля 2020

У меня есть один дешевый товар. Я хочу отдать этот продукт, если и только если промежуточный итог корзины составляет 200 или больше.

Если промежуточный итог корзины составляет 200 или больше, добавьте продукт в корзину и установите цену равной 0.

Если промежуточный итог корзины меньше 200, удалите продукт из корзины.

При добавлении и удалении я использую уведомление, чтобы сообщить покупателю. Все работает по плану, кроме изменения цены продукта.

Если кто-то может проверить код, который я использую, и исправить одну вещь, я был бы очень благодарен.

add_action( 'woocommerce_before_calculate_totals', 'free_product_if_cart_minimum', 10, 1 );
function free_product_if_cart_minimum( $cart ) {

    // go away if admin
    if (is_admin() && !defined( 'DOING_AJAX' )) return;

    // say no to hook repetition 
    if (did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;

    $minimum_amount = 200;
    $free_product_id = 4576;
    $cart_items_total = 0;

    // cart loop
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
    
        // is the free product there?
        if ( $cart_item['data']->get_id() == $free_product_id ) {
        
            $free_item_key = $cart_item_key;

        // set the price to zero
        // I've tried them both without success
        
        // $free_item_key->set_price( 0 );
        // $free_product_id->set_price( $price * 0.00 );
    }
    
    // cart subtotal incl. tax and discounts
    $cart_items_total += $cart_item['line_total'] + $cart_item['line_tax'];
    
    }

    // add the free product if not already there
    if ( $cart_items_total >= $minimum_amount && !isset( $free_item_key ) ) {

        $cart->add_to_cart( $free_product_id );

        wc_add_notice( 'Thank you! Here\'s your free product.', 'notice' );
    }

    // if below the minimum, remove the free product
    elseif ( $cart_items_total < $minimum_amount && isset( $free_item_key ) ) {

        $cart->remove_cart_item( $free_item_key );

        // display notice after removal
        wc_add_notice( 'Your cart subtotal is less than 200 and therefore, the free product was removed.', 'notice' );
    }
}

1 Ответ

1 голос
/ 10 июля 2020
• 1000 . Проверено и работает.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...