【问题标题】:Add a discount for specific selected payment method in WooCommerce在 WooCommerce 中为特定选择的付款方式添加折扣
【发布时间】:2018-06-05 23:11:18
【问题描述】:

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

我想帮助确定要使用的挂钩。我想要实现的总体思路是:

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

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

【问题讨论】:

    标签: php wordpress woocommerce checkout discount


    【解决方案1】:

    您可以在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
    }
    

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

    经过测试并且有效。

    【讨论】:

    • 漂亮,正是我想要的。谢谢 Loic!
    【解决方案2】:

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

    if (($chosen_payment_method == 'stripe' || $chosen_payment_method == 'paypal') && current_user_can('dealer')) {
    

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 2016-11-19
      • 2020-04-04
      • 1970-01-01
      • 2014-02-09
      • 2016-11-17
      • 2016-04-01
      • 2018-12-23
      • 2015-04-01
      相关资源
      最近更新 更多