更新时间:2023-11-30 11:54:16
以下代码将在有针对性的付款方式下向购物车提供2%的折扣只能由用户用户在结帐页面上选择:
The following code will apply a discount of 2% to cart when a targeted payment method has been selected by a subscriber user role only on checkout page:
// 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文件中显示主题(或活动主题)。经过测试并可以正常工作。
This code goes on function.php file of your active child theme (or active theme). tested and works.
所需的付款方式ID ,您将必须使用浏览器检查器工具检查围绕付款方式单选按钮的html代码:
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: