Advertisement
tommyosheawebdesign

Hide payment method based on product type in WooCommerce

Feb 16th, 2019
746
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.56 KB | None | 0 0
  1. Here is an example with a custom hooked function in woocommerce_available_payment_gateways filter hook, where I can disable payment gateways based on the cart items (product type):
  2.  
  3. add_filter('woocommerce_available_payment_gateways', 'conditional_payment_gateways', 10, 1);
  4. function conditional_payment_gateways( $available_gateways ) {
  5.     // Not in backend (admin)
  6.     if( is_admin() )
  7.         return $available_gateways;
  8.  
  9.     foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
  10.         $prod_variable = $prod_simple = $prod_subscription = false;
  11.         // Get the WC_Product object
  12.         $product = wc_get_product($cart_item['product_id']);
  13.         // Get the product types in cart (example)
  14.         if($product->is_type('simple')) $prod_simple = true;
  15.         if($product->is_type('variable')) $prod_variable = true;
  16.         if($product->is_type('subscription')) $prod_subscription = true;
  17.     }
  18.     // Remove Cash on delivery (cod) payment gateway for simple products
  19.     if($prod_simple)
  20.         unset($available_gateways['cod']); // unset 'cod'
  21.     // Remove Paypal (paypal) payment gateway for variable products
  22.     if($prod_variable)
  23.         unset($available_gateways['paypal']); // unset 'paypal'
  24.     // Remove Bank wire (Bacs) payment gateway for subscription products
  25.     if($prod_subscription)
  26.         unset($available_gateways['bacs']); // unset 'bacs'
  27.  
  28.     return $available_gateways;
  29. }
  30.  
  31. Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
  32.  
  33. All code is tested on Woocommerce 3+ and works.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement