根据付款和重量自动在购物车中应用优惠券

时间:2020-02-09 17:12:12

标签: php wordpress woocommerce checkout coupon

如果所有产品的重量都超过10kg,并且仅在“鳕鱼”付款网关上,我想在结帐时自动应用优惠券代码。我从其他答案中获得了代码,并且几乎可以正常工作,但是有一件奇怪的事。在if语句应用优惠券时,if之后,我的购物车没有计算,只是冻结。第二个if语句正常工作。我不明白为什么会这样。我究竟做错了什么?

基于Apply a coupon programmatically in Woocommerce答案代码,这是我的尝试:

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

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

    // Initializing variables
    $coupon_code      = 'predoplata'; // Coupon code
    $weight_threshold = 10; // Total weight threshold

    $total_weight     = $cart->get_cart_contents_weight();
    $applied_coupons  = $cart->get_applied_coupons();
    $coupon_code      = sanitize_text_field( $coupon_code );

    $payment_method = 'cod';
    $chosen_payment_method = WC()->session->get('chosen_payment_method');
    $payment = false;
    if ($payment_method == $chosen_payment_method) {
        $payment = true;
    }

    // Applying coupon
    if( (! in_array($coupon_code, $applied_coupons) && $total_weight >= $weight_threshold) && ($payment) ){
        $cart->add_discount( $coupon_code );
    }
    // Removing coupon
    elseif ( (in_array($coupon_code, $applied_coupons) && $total_weight < $weight_threshold) || (! $payment) ) {
        $cart->remove_coupon($coupon_code);
    }
}

然后我检查用户是否更改了付款网关

add_action( 'woocommerce_review_order_before_payment', 'payment_methods_trigger_update_checkout' );
function payment_methods_trigger_update_checkout(){
    // jQuery code
    ?>
    <script type="text/javascript">
        (function($){
            $( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
                setTimeout(function(){
                    $(document.body).trigger('update_checkout');
                }, 250 );
            });
        })(jQuery);
    </script>
    <?php
}


add_action( 'woocommerce_checkout_update_order_review', 'refresh_shipping_methods' );
function refresh_shipping_methods( $post_data ){
    WC()->cart->calculate_shipping();
}

在使用优惠券时会发生以下情况:

Here is what happens when coupon is applying

0 个答案:

没有答案