WooCommerce Hide Payment Gateway for Custom Attribute

Viewed 92

Just starting in my WordPress/WooCommerce journey.

I found a question on here from a while back asking about restricting payment gateways for a specific attribute selection. I've tried to integrate this into my site and I cannot get it working! I've added the Attribute and Terms, and the slugs are as follows - pay_now_deposit (attr) and pay_now / deposit (terms).

I'm looking to restrict Klarna payments for those paying by deposit, and the code I have is below -

function conditional_payment_gateways( $available_gateways ) {
   $in_cart = false;
   foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
       // See if there is an attribute called 'pa_size' in the cart
       // Replace with whatever attribute you want
       if (array_key_exists('pa_pay_now_deposit', (array) $values['data']->get_attributes() ) ) {
       foreach ($values['data']->get_attributes() as $attribute => $variation);
           // Replace 'small' with your value.  
           if ($variation == 'deposit') $in_cart = true; //edited
      } 
   }
   if ( $in_cart ) {
       unset($available_gateways['klarna_payments']); 
   }
   else {
       unset($available_gateways['cod']);
   }
   return $available_gateways;
}

Any advice on where I'm going wrong would be greatly appreciated!

1 Answers

Try to add a break statement.

add_filter('woocommerce_available_payment_gateways', 'conditional_payment_gateways', 10, 1);
function conditional_payment_gateways( $available_gateways ) {

    $in_cart = false;

    foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
        
        if ( array_key_exists( 'pa_pay_now_deposit', (array) $values['data']->get_attributes() ) ) {
            foreach ( $values['data']->get_attributes() as $attribute => $variation ){
                if ( $variation == 'deposit' ){
                    $in_cart = true; //edited
                    break;
                }   
            }
        } 
        if( $in_cart ){
            break;
        }

    }
    
    if ( $in_cart ) {
        unset( $available_gateways['klarna_payments'] ); 
    }else {
        unset( $available_gateways['cod'] );
    }

    return $available_gateways;
}
Related