jquery WooCommerce根据结账屏幕上的付款方式添加折扣

jljoyd4f  于 5个月前  发布在  jQuery
关注(0)|答案(1)|浏览(62)

我试图在我的WooCommerce商店中添加“支票”付款的折扣,但WC()->session->get('chosen_payment_method')命令无法按预期工作。我可以成功添加折扣,但我无法使其依赖于所选的付款方式。我在.zip文件中的.php文件中有此文件,并在我的WordPress网站上运行它作为自定义插件。
这是我当前的代码。WC()->session->get('chosen_payment_method')似乎没有按预期工作,导致if($chosen_payment_method == 'chee')语句无法运行。

add_filter( 'woocommerce_cart_calculate_fees', 'discount_based_on_payment_method', 10, 1 );

function discount_based_on_payment_method( $cart ) {
    
    $targeted_payment_method = 'cheque'; // Using the cheque payment method
    $chosen_payment_method = WC()->session->get('chosen_payment_method');
    var_dump($chosen_payment_method); //this is for debugging. it always shows NULL
    
    if($chosen_payment_method == 'cheque') {
        $discount = $cart->subtotal * 0.10; // 10% discount
        $cart->add_fee( 'Cash Discount', -$discount);
    }
    
    // jQuery code: Make dynamic text button "on change" event ?>
    <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")
                }
            };
            t.trigger_update_checkout();
        });
    })(jQuery);
    </script><?php
    
    //$cart->add_fee( 'Test Discount', '10' );
}

字符串

lsmd5eda

lsmd5eda1#

为了更好地检查某些东西,在过滤器钩子中使用error_log(),而不是echovar_dump()print_r().
使用以下命令代替:

add_action( 'woocommerce_checkout_init', 'payment_method_change_trigger_update_checkout_js' );
function payment_method_change_trigger_update_checkout_js() {
    wc_enqueue_js("$('form.checkout').on( 'change', 'input[name=payment_method]', function(){
        $(document.body).trigger('update_checkout');
    });");
}

add_filter( 'woocommerce_cart_calculate_fees', 'discount_based_on_payment_method', 10, 1 );
function discount_based_on_payment_method( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return;
    
    $targeted_payment_method = 'cheque'; // Here define the desired payment method
    
    if( WC()->session->get('chosen_payment_method') === $targeted_payment_method ) {
        $discount = $cart->subtotal * 0.10; // 10% discount
        $cart->add_fee( 'Cash Discount', -$discount);
    }
}

字符串
代码放在你的子主题的functions.php文件中(或插件中)。测试和工作。
相关:如何在WooCommerce 3+中调试

相关问题