首页 文章

根据Woocommerce中的特定购物车数量自动申请优惠券

提问于
浏览
1

我正在尝试自动触发优惠券,以便在购物车中有4个商品时专门用于购物车 .

优惠券是在网站的Woocommerce后端预先创建的"tasterbox"

我正在使用此答案代码的修订版本:
Add WooCommerce coupon code automatically based on product categories

这是我的代码版本:

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 回答

  • 1

    您的代码中存在一些小错误和错误 . 请尝试以下方法:

    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文件中 . 经过测试和工作 .

相关问题