You don’t always want all visitors to be able to use all payment methods. Especially if they are new customers, you are used to being a bit more cautious. By default, however, only all payment methods can be globally activated or deactivated.
This can be conveniently customized with just a few lines of code.
The finished code #
We start as usual with the complete code, which you can simply add to functions.php.
<?php
function setPaymentOptionsByUserRole( $availablePaymentGateways ) {
if ( is_user_logged_in() ) {
$allowedPaymentGateways = array();
$user = wp_get_current_user();
if ( array_intersect( array('merchant'), $user->roles )) {
$allowedPaymentGateways = array(
'bacs',
'direct-debit',
'ppec_paypal',
'paypal_plus',
);
}
if(!empty($allowedPaymentGateways)) {
foreach ( $availablePaymentGateways as $slug => $gateway ) {
if ( ! in_array( $slug, $allowedPaymentGateways ) ) {
unset( $availablePaymentGateways[ $slug ] );
}
}
}
}else{
/*
* We can use the else loop to change the payment gateways for
* guests.
*/
$allowedPaymentGateways = array(
'bacs',
'direct-debit',
'ppec_paypal',
'paypal_plus',
);
if(!empty($allowedPaymentGateways)) {
foreach ( $availablePaymentGateways as $slug => $gateway ) {
if ( ! in_array( $slug, $allowedPaymentGateways ) ) {
unset( $availablePaymentGateways[ $slug ] );
}
}
}
}
return $availablePaymentGateways;
}
add_filter('woocommerce_available_payment_gateways', 'setPaymentOptionsByUserRole', 90, 1);
The whole thing can be extended endlessly. In our example we have limited the payment methods for all users with the user role “merchant” to PayPal, bank transfer, direct debit and credit card.
if ( array_intersect( array('merchant'), $user->roles )) {
$allowedPaymentGateways = array(
'bacs',
'direct-debit',
'ppec_paypal',
'paypal_plus',
);
}
All other payment methods will be removed afterwards.
if(!empty($allowedPaymentGateways)) {
foreach ( $availablePaymentGateways as $slug => $gateway ) {
if ( ! in_array( $slug, $allowedPaymentGateways ) ) {
unset( $availablePaymentGateways[ $slug ] );
}
}
}
This is how you can restrict additional roles #
You can add more roles by copying and pasting the following block directly below.
if ( array_intersect( array('<user_role>'), $user->roles )) {
$allowedPaymentGateways = array();
}
Replace ” with the desired user role.
WordPress user role | Slug |
Editor | editor |
Author | author |
Administrator | administrator |
Contributor | contributor |
Subscriber | subscriber |
That’s about it. With a few lines of code, you can easily customize the payment process. I hope this article was helpful for you. If you have any questions, we will be happy to answer them for you.
Comments