Добавить или удалить указанную c корзину Товар, основанный на общей сумме корзины WooCommerce - PullRequest
2 голосов
/ 11 марта 2020

Я пытаюсь добавить бесплатный продукт в корзину, если сумма заказа превышает $ 199,99

Я достиг этого, и он работает. Проблема заключается в том, что мне нужно удалить продукт, если пользователь затем удаляет товар из корзины и снова опускается ниже 199,99 долл. (Для предотвращения игры в системе).

То, что у меня, похоже, работает. Проблема в том, что мне кажется, что мне нужно щелкнуть 2 ссылки, прежде чем кажется, что действие УДАЛИТЬ ИЗ КОРЗИНЫ работает (или обновить sh страницу).

Что вызывает это? Можно ли случайно выполнить действие удаления с помощью AJAX?

// -------------------------------------------
// ADD PRODUCT IF ORDER MINIMUM ABOVE 200

/*
* Automatically adding the product to the cart when cart total amount reach to $199.99.
*/

function aapc_add_product_to_cart() {
    global $woocommerce;

    $cart_total = 199.99;   

    if ( $woocommerce->cart->total >= $cart_total ) {
        if ( is_user_logged_in() ) {
            $free_product_id = 339;  // Product Id of the free product which will get added to cart
            $found      = false;

            //check if product already in cart
            if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
                foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                    $_product = $values['data'];
                    if ( $_product->get_id() == $free_product_id )
                        $found = true;                  
                }
                // if product not found, add it
                if ( ! $found )
                    WC()->cart->add_to_cart( $free_product_id );
            } else {
                // if no products in cart, add it
                WC()->cart->add_to_cart( $free_product_id );
            }        
        }
    }
    if ( $woocommerce->cart->total <= $cart_total && $found ) {
                WC()->cart->remove_cart_item( $free_product_id );
            }       
}

add_action( 'template_redirect', 'aapc_add_product_to_cart' );

add_action( 'template_redirect', 'remove_product_from_cart_programmatically' );

function remove_product_from_cart_programmatically() {
    if ( is_admin() ) return;
    $product_id = 339; // product id
    $cart_total = 199.99;
    $in_cart = false;
    foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        if ( $cart_item['product_id'] === $product_id ) {
            $in_cart = true;
            $key = $cart_item_key;
            break;
        }
    }
    if( WC()->cart->total < $cart_total ) {
        if ( $in_cart ) WC()->cart->remove_cart_item( $key );
    }
}

1 Ответ

2 голосов
/ 11 марта 2020

Вы не должны использовать template_redirect ловушку для добавления или удаления бесплатного продукта на основе общей пороговой суммы корзины ... Кроме того, ваш код несколько устарел с некоторыми ошибками.

Вместо этого используйте woocommerce_before_calculate_totals ловушку, которая Ajax включена, таким образом:

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

    // ONLY for logged users (and avoiding the hook repetition) 
    if ( ! is_user_logged_in() && did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $threshold_amount = 200; // The threshold amount for cart total
    $free_product_id  = 339; // ID of the free product
    $cart_items_total = 0; // Initicializing

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
        // Check if the free product is in cart
        if ( $cart_item['data']->get_id() == $free_product_id ) {
            $free_item_key = $cart_item_key;
        }
        // Get cart subtotal incl. tax from items (with discounts if any)
        $cart_items_total += $cart_item['line_total'] + $cart_item['line_tax'];
    }

    // If Cart total is up to the defined amount and if the free products is not in cart, we add it.
    if ( $cart_items_total >= $threshold_amount && ! isset($free_item_key) ) {
        $cart->add_to_cart( $free_product_id );
    }
    // If cart total is below the defined amount and free product is in cart, we remove it.
    elseif ( $cart_items_total < $threshold_amount && isset($free_item_key) ) {
        $cart->remove_cart_item( $free_item_key );
    }
}

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

Похожие: Другие похожие темы ответов

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