I’m struggling with applying a fee for an array of user roles if and when a specific payment gateway is selected.
The code I’ve written works fine if I do not check the user role, but once I try and do that, it does not.
I’ve removed (commented) the user role if
statement in the code and I’m asking for help making it work.
I need to check if the user role match my array
and if it does, check the payment gateway. If the payment gateway match too, apply the fee.
This is my code:
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee', 20, 1 );
function custom_fee ($cart){
if (is_admin() && !defined('DOING_AJAX')) return;
if (!is_user_logged_in()) return;
if (!is_checkout() && !is_wc_endpoint_url()) return;
$customer_role = wp_get_current_user();
$roles_to_check = array( 'vendor', 'external' );
$payment_method = WC()->session->get('chosen_payment_method');
// if (!in_array($roles_to_check, $customer_role->roles)) return;
if ('bacs' == $payment_method){
$payment_fee = $cart->subtotal * 0.05;
$cart->add_fee( 'Payment Fee', $payment_fee, true );
}
}
2
Answers
You could use the following, explanation with comments added in the code
Conditions that must be met in this code are:
EDIT
To complete my answer, see the answer from @LoicTheAztec
The answer of @7uc1f3r is good, but something important is missing from it.
In WooCommerce checkout when choosing a payment method, checkout totals are not refreshed. So something additional is required to refresh checkout "order review" section:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Related: Add fee based on specific payment methods in WooCommerce