ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-12 07:33:03  阅读:327  来源: 互联网

标签:checkout php wordpress woocommerce hook-woocommerce


我正在尝试为functions.php创建一个代码段,当同时选择了角色“ subscriber”和付款方式“ credit-card”时,将为购物车总额带来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' );

谁能帮忙完成此任务?还是至少指向正确的方向?

解决方法:

当订户用户角色仅在结帐页面上选择了定向付款方式时,以下代码将为购物车提供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

To get the correct desired Payment methods IDs, you will have to inspect the html code around the payment methods radio buttons searching with your browser inspector tools:

07001

标签:checkout,php,wordpress,woocommerce,hook-woocommerce
来源: https://codeday.me/bug/20191012/1898544.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有