1
votes

In Woocommerce, i want to hide the credit card payment option if a specific product variation is in the cart. Please help.

Thanks.

This is what i have working now. I assigned a separate shipping class to each variation i want to disable a specific payment method at checkout. But it would be much easier if i coud target specific attribute values, so i don't have to assign a shipping class.

 <?php


add_filter('woocommerce_available_payment_gateways', 'conditional_payment_gateways', 10, 1);

function conditional_payment_gateways( $available_gateways ) {
   $shipping_class_target = 106; // the shipping class ID assigned to specific variations 
   $in_cart = false;
   foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
      if ( $values[ 'data' ]->get_shipping_class_id() == $shipping_class_target ) {
         $in_cart = true;
         break;
      } 
   }
   if ( $in_cart ) {
       unset($available_gateways['cod']); // unset 'cod' 

   }
   else {
       unset($available_gateways['bacs']); // unset 'bacs' 

   }
   return $available_gateways;
}
1
Yes, i did. Have you tried not jumping to conclusions?Adrian P.
Your code works when I test it. Are you sure you have the right shipping class target?Howard E
It works on my side also. But i wish i could make it work without using shipping classes. Basically i don't know how to check the product variations for each cart item.Adrian P.

1 Answers

1
votes

If you are looking to check the variations for each item in the cart, you have to lookup the attributes $product->get_attributes() and then loop through those and get the array key and value for each.

In this example, I used

Size (pa_size) and Small

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 ) {
       // See if there is an attribute called 'pa_size' in the cart
       // Replace with whatever attribute you want
       if (array_key_exists('pa_size', (array) $values['data']->get_attributes() ) ) {
       foreach ($values['data']->get_attributes() as $attribute => $variation);
           // Replace 'small' with your value.  
           if ($variation == 'small') $in_cart = true; //edited
      } 
   }
   if ( $in_cart ) {
       unset($available_gateways['cod']); // unset 'cod' 

   }
   else {
       unset($available_gateways['bacs']); // unset 'bacs' 

   }
   return $available_gateways;
}