首页 > 解决方案 > 根据选择的付款方式更改 Woocommerce 购物车项目税类

问题描述

我已尝试在特定用户的许多答案中实现在此站点上找到的代码,以根据所选支付网关的更改或其他一些字段更改刷新结帐。但是,当 JS 包含在我的函数文件中时,我的结帐卡住了,并且我有 ajax 加载动画圆圈。

我已经尝试从以下位置调整代码:

在 Woocommerce 中的运输方式更改时触发 ajax update_checkout 事件

在 Woocommerce 中选择支付网关时更新结帐 ajax 事件

在 Woocommerce 中更改国家/地区更改 ajax 更新结帐以进行运输

根据 Woocommerce 选择的付款方式更改结帐时的付款按钮

add_filter( "woocommerce_product_get_tax_class", "woo_diff_rate_for_user", 1, 2 );
add_filter( "woocommerce_product_variation_get_tax_class", "woo_diff_rate_for_user", 1, 2 );
function woo_diff_rate_for_user( $tax_class, $product ) {

// Get the chosen payment gateway (dynamically)
$chosen_payment_method = WC()->session->get('chosen_payment_method');

 if( $chosen_payment_method == 'wdc_woo_credits'){
        $tax_class = "Zero rate";
    } 

<script type="text/javascript">
        (function($){
            $('form.checkout').on( 'change', 'input[name^="payment_method"]', function() {
                var t = { updateTimer: !1,  dirtyInput: !1,
                    reset_update_checkout_timer: function() {
                        clearTimeout(t.updateTimer)
                    },  trigger_update_checkout: function() {
                        t.reset_update_checkout_timer(), t.dirtyInput = !1,
                        $(document.body).trigger("update_checkout")
                    }
                };
                $(document.body).trigger('update_checkout')
            });
        })(jQuery);
    </script>
     return $tax_class;
}

如果我不包含 JS/jQuery,我的函数会在更改运输方式并且页面在更改时刷新时根据付款选项更改税级。但是我需要在支付网关更改时而不是在更改运输时刷新结帐。

标签: phpjquerywordpresswoocommercepayment-method

解决方案


您不能在过滤器挂钩中包含这种 jQuery 脚本,并且您的代码中存在错误。无论如何,即使更改税级,您也没有使用正确的代码。

替换代码:

add_action( 'woocommerce_before_calculate_totals', 'change_tax_class_based_on_payment_method', 10, 1 );
function change_tax_class_based_on_payment_method( $cart ) {
    // Only for a specific defined payment meyhod
    if ( WC()->session->get('chosen_payment_method') !== 'wdc_woo_credits' )
        return;

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

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

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ){
        // We set "Zero rate" tax class
        $cart_item['data']->set_tax_class("Zero rate");
    }
}

add_action('wp_footer', 'payment_methods_trigger_update_checkout');
function payment_methods_trigger_update_checkout() {
    if( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type="text/javascript">
        jQuery(function($){
            $( 'form.checkout' ).on('change', 'input[name="payment_method"]', function() {
                $(document.body).trigger('update_checkout');
            });
        });
    </script>
    <?php
    endif;
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

如果您使用Woo Credits插件,正确的付款 ID 是woo_credits,但不是wdc_woo_credits


推荐阅读