skip to Main Content

Please Guys,

I use two payment gateways on the checkout page:

1° bacs = Bank transfer
2° cod = Cash on Delivery

i need to hide the payment gateway COD = Cash on Delivery, If the user has No Admin Profile (!is_user_admin()), || or it’s not logged, || ! is_user_logged_in() then hide.

This is the code that i’m using and it’s working.

add_filter( 'woocommerce_available_payment_gateways', 'bbloomer_cod_hide' );
  
function bbloomer_cod_hide( $available_gateways ) {
   if ( isset( $available_gateways['cod']) && !is_user_admin() ) {
      unset( $available_gateways['cod'] );
   } 
   return $available_gateways;
}

The problem is…the payment gateway bacs = Bank transfer is also affected and hidden : )

so i tried with this another hook

add_filter( 'woocommerce_available_payment_gateways', 'transfer_enable_bacs' );
  
function transfer_enable_bacs( $available_gateways ) {
   if ( isset( $available_gateways['bacs']) && !is_user_admin() ) {
      //unset( $available_gateways['bacs'] );
   } 
   return $available_gateways;
}

But this is not the correct solution. Both payment gateways are hidden.

What am i doing wrong please?
Gratitude!

2

Answers


  1. I think you need to replace is_user_admin with current_user_can

    add_filter( 'woocommerce_available_payment_gateways', 'bbloomer_cod_hide' );
          
        function bbloomer_cod_hide( $available_gateways ) {
           if ( isset( $available_gateways['cod'] ) && ! current_user_can( 'administrator' ) ) {
              unset( $available_gateways['cod'] );
           } 
           return $available_gateways;
        }
    

    is_user_admin does not check if the user is an administrator; use current_user_can() for checking roles and capabilities.

    https://developer.wordpress.org/reference/functions/is_user_admin/

    Login or Signup to reply.
  2. try the following code:

    add_filter( ‘woocommerce_available_payment_gateways’, ‘bbloomer_cod_hide’ );

    function bbloomer_cod_hide( $available_gateways ) {
       if ( !is_user_logged_in() ) || !current_user_can( 'install_themes' ) ) {
          unset( $available_gateways['cod'] );
       } 
       return $available_gateways;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search