PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, March 12, 2022

[FIXED] Woocommerce - Hide payment method if specific variation is in cart

 March 12, 2022     woocommerce, wordpress     No comments   

Issue

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;
}

Solution

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;
}


Answered By - Howard E
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing