且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为WooCommerce中特定的选定付款方式添加折扣

更新时间:2023-11-30 11:54:28

您可以使用 woocommerce_cart_calculate_fees 动作挂钩中挂接的此自定义函数,对于定义的付款方式,该挂钩将有15%的折扣.

You can use this custom function hooked in woocommerce_cart_calculate_fees action hook, that will make a discount of 15% for a defined payment method.

您应该在此功能中设置您的实际付款方式ID(例如"bacs",鳕鱼",支票"或贝宝").

You should need to set in this function your real payment method ID (like 'bacs', 'cod', 'cheque' or 'paypal').

每次选择付款方式时,第二个功能都会刷新结帐数据.

The 2nd function will refresh checkout data each time that a payment method is selected.

代码:

add_action( 'woocommerce_cart_calculate_fees','shipping_method_discount', 20, 1 );
function shipping_method_discount( $cart_object ) {

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

    // HERE Define your targeted shipping method ID
    $payment_method = 'bacs';

    // The percent to apply
    $percent = 15; // 15%

    $cart_total = $cart_object->subtotal_ex_tax;
    $chosen_payment_method = WC()->session->get('chosen_payment_method');

    if( $payment_method == $chosen_payment_method ){
        $label_text = __( "Shipping discount 15%" );
        // Calculation
        $discount = number_format(($cart_total / 100) * $percent, 2);
        // Add the discount
        $cart_object->add_fee( $label_text, -$discount, false );
    }
}

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

代码进入您的活动子主题(或活动主题)的function.php文件中.

Code goes in function.php file of your active child theme (or active theme).

经过测试,可以正常工作.

Tested and works.