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

问题描述 投票:1回答:2

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

我想帮助确定使用哪些钩子。我希望实现的一般想法是:

if payment_method_hook == 'xyz'{
    cart_subtotal = cart_subtotal - 15%
}

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

php wordpress woocommerce checkout discount
2个回答
2
投票

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

您应该在此功能中设置真实的付款方式ID(例如'bacs','cod','check'或'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
}

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

经过测试和工作。


0
投票

这可能有助于其他人..我需要检查2种方法的付款方式并检查用户是否是特定角色。

if (($chosen_payment_method == 'stripe' || $chosen_payment_method == 'paypal') && current_user_can('dealer')) {
© www.soinside.com 2019 - 2024. All rights reserved.