我正在尝试在 WooCommerce 商店中为“支票”付款添加折扣,但 WC()->session->get('chosen_ payment_method') 命令未按预期工作。我可以成功添加折扣,但无法使其取决于所选的付款方式。我将其放在 .zip 文件内的 .php 文件中,并在我的 WordPress 网站上将其作为自定义插件运行。
这是我当前的代码。 WC()->session->get('chosen_ payment_method') 似乎没有按预期工作,并导致 if($chosen_ payment_method == 'cheque') 语句无法运行。
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' );
}
要更好地检查某些内容,请在过滤器挂钩中使用
error_log()
,但不要使用 echo
、var_dump()
或 print_r()
…然后不要在过滤器挂钩中回显/输出任何 JavaScript。
请使用以下内容:
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;
$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 文件中(或插件中)。已测试并有效。