Disable Payment Gateways based on User Role

In this tutorial I will show you how to enable or disable WooCommerce payment gateways for a specific user role. And also how to condition them for registered users.

If you need custom coding help with WooCommerce payment gateways – contact me.

All the code below is based on woocommerce_available_payment_gateways filter hook and can be inserted to your current or child theme functions.php file or a custom plugin.

Disable Payment Methods for a Specific User Role

/**
 * @snippet       Disable WooCommerce Payment Gateway for a Specific User Role
 * @author        Misha Rudrastyh
 * @url           https://rudrastyh.com/woocommerce/disable-payment-gateway-by-user-role.html
 */
add_filter( 'woocommerce_available_payment_gateways', 'rudr_turn_off_cod' );
  
function rudr_turn_off_cod( $available_gateways ) {
	
	if( current_user_can( 'subscriber' ) ) {
		if ( isset( $available_gateways[ 'cod' ] ) ) {
			unset( $available_gateways[ 'cod' ] );
		}
		// if you need to disable multiple payment gateways just add similar code
		// if ( isset( $available_gateways[ 'payment_gateway_2' ] ) ) {
		//		unset( $available_gateways[ 'payment_gateway_2' ] );
		// }
	}

	return $available_gateways;
}
  • If you don’t how to get a user role, remember that there are default user roles, like subscriber, author, contributor, editor and administrator and there are a couple default roles in WooCommerce too – customer and shop_manager.
  • What about a payment gateway ID? How to get it? If you uncomfortable with inspecting source code in your browser, I think the best way is to add a payment gateway ID column.
  • If you want to disable a payment method for multiple user roles, you can condition it like current_user_can( 'subscriber' ) || current_user_can( 'author' ).

Enable Payment Methods for a Specific User Role

Code is very similar to a previous snippet, the difference is just one symbol! So I just copy the part of it.

if( ! current_user_can( 'subscriber' ) ) {

So we disable our payment gateways for any user role except Subscriber role.

Enable Payment Gateway for Registered Users

This code is also based on a snippet I showed you before, all you need to do is just to change one line of it.

if( ! is_user_logged_in() ) {

So the result is that we disable payment gateway for all users who is not logged in.

Share:

Leave a Reply