Woocommerce中基于用户角色和付款方式的折扣百分比

时间:2018-07-15 20:36:48

标签: php wordpress woocommerce checkout hook-woocommerce

我正在尝试为functions.php创建一个代码段,当同时选择了角色“ subscriber”和付款方式“ credit-card”时,将为购物车总额带来2%的折扣。我到目前为止的进展

mainWindow.loadFile('teacher.html')

有人可以帮助完成此操作吗?还是至少指向正确的方向?

1 个答案:

答案 0 :(得分:2)

当订户用户角色仅在结帐页面上选择了定向付款方式时,以下代码将向购物车提供2%的折扣:

// Applying conditionally a discount
add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_user_role_and_payment', 20, 1 );
function discount_based_on_user_role_and_payment( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return; // Exit

    // Only on checkout page for 'subscriber' user role
    if ( ! ( is_checkout() && current_user_can('subscriber') ) )
        return; // Exit

    // HERE Below define in the array your targeted payment methods IDs
    $targeted_payment_methods = array( 'paypal', 'stripe' );
    // HERE define the percentage discount
    $percentage = 2;

    if( in_array( WC()->session->get('chosen_payment_method'), $targeted_payment_methods ) ){
        // Calculation
        $discount = $cart->get_subtotal() * $percentage / 100;
        // Applying discount
        $cart->add_fee( sprintf( __("Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
    }
}

// Refreshing totals on choseen payment method change event
add_action( 'woocommerce_review_order_before_payment', 'refresh_payment_methods' );
function refresh_payment_methods(){
    // Only on checkout page
    if ( ! ( is_checkout() && current_user_can('subscriber') ) ) return;
    // 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文件中。经过测试并可以正常工作。

enter image description here

  

要获取正确的所需付款方式ID ,您必须检查使用浏览器检查工具搜索的付款方式单选按钮周围的html代码:

     

enter image description here