Filter available WooCommerce payment gateways by role [closed]

Arrrrg a WooCommerce question… quick burn him at the stake!

There’s a couple of problems with your callback function above:

  • you are not declaring global $woocommerce so you do not have access to the $woocommerce global variable.
  • and $woocommerce->customer holds the state of the WC_Customer class however this class does not contain a get_role() method, further more you are not defining anywhere in your callback the value of the $role variable so that wouldn’t work anyway even if the method existed.

Instead, check for the user role in the roles array returned on the WP_User object:

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_private' );

 function payment_gateway_disable_private( $available_gateways ) {

    $user = wp_get_current_user();

    if ( isset( $available_gateways['authorize'] ) && in_array('company', $user->roles) ) {
        unset( $available_gateways['authorize'] );
    } else if ( isset( $available_gateways['cheque'] ) && in_array('customer', $user->roles)  ) {
        unset( $available_gateways['cheque'] );
    }

   return $available_gateways;

}

Note: if the user is logged out, they will have no role, so you may wish to account for that and do something different such as redirect the user to login first before shopping depending on your use case, you can use is_user_logged_in() for that.

Leave a Comment