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

Eva*_*van 5 php wordpress checkout discount woocommerce

如果没有使用优惠券功能,我想对特定付款方式 ID(例如“xyz”)应用 15% 的折扣。

我需要帮助确定要使用哪些钩子。我想要实现的总体想法是:

if payment_method_hook == 'xyz'{
    cart_subtotal = cart_subtotal - 15%
}
Run Code Online (Sandbox Code Playgroud)

客户不需要在此页面上看到折扣。我希望正确提交折扣,仅适用于特定的付款方式。

Loi*_*tec 9

您可以使用挂接到操作挂钩中的此自定义函数woocommerce_cart_calculate_fees,这将为定义的付款方式提供 15% 的折扣。

您应该需要在此函数中设置您的真实付款方式 ID (例如“bacs”、“cod”、“cheque”或“paypal”)

第二个功能将在每次选择付款方式时刷新结账数据。

代码:

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
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的 function.php 文件中。

经过测试并有效。