【问题标题】:Percentage discount based on user role and payment method in WoocommerceWoocommerce 中基于用户角色和付款方式的百分比折扣
【发布时间】:2018-12-23 10:11:28
【问题描述】:

我试图为functions.php创建一个代码sn-p,当角色“订阅者”和支付方式“信用卡”都被选中时,它将对购物车总数应用2%的折扣。到目前为止我的进步

function discount_when_role_and_payment(/* magic */) {
global $woocommerce;
if ( /* credit-card selected */ && current_user_can('subscriber') ) {
    /* get woocommerce cart totals, apply 2% discount and return*/
} 
return /*cart totals after discount*/;
}

add_filter( '/* magic */', 'discount_when_role_and_payment' );

谁能帮忙完成这个?或者至少指向正确的方向?

【问题讨论】:

    标签: php wordpress woocommerce checkout hook-woocommerce


    【解决方案1】:

    当订阅者用户角色仅在结帐页面上选择了目标付款方式时,以下代码将对购物车应用 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 文件中。经过测试并且有效。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 2016-11-19
      • 2021-08-09
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      相关资源
      最近更新 更多