Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Remove payment gateway if product is in the cart (Woocommerce) WordPress

  • SOLVED

In my Woocommerce setup, I have two payment gateways. If specific products (id) is in the cart, I want to show gateway_2 and hide gateway_1. If that product is NOT in the cart, then show "gateway_1" and hide gateway_2.

Can anyone help me with a function code for this?

Thanks

Answers (2)

2016-12-04

Bob answers:

Here is code which should work.


function is_product_in_cart( $prodid ){
$product_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
if ( $product->id == $prodid ) {
$product_in_cart = true;
}

}
return $product_in_cart;
}
// Disable gateway based on country
function payment_gateway_disable_product( $available_gateways ) {
global $woocommerce;
//print_r( $available_gateways );
if ( isset( $available_gateways['paypal'] ) && is_product_in_cart( 14 ) ) {
unset( $available_gateways['paypal'] );
}
return $available_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_product' );


in above example it will disable paypal payment gateway for product id with 14

you have to set payment gateway and product id in above code to match your need.
you can add if else statement and disable multiple gateways based on your need.


George Sprouse comments:

Hi, thank you is there anyway to add multiple product id?


Bob comments:

Yes we can pass an array of product ids and check cart product ids within that array using in_array function()

you have two payment gateways so you need if else statement so if condition is true then hide second gateways and if condition is false then hide first gateway.

In below code I used two gateways for example paypal and cod. if cart has product from available array then it will show hide paypal otherwise it will hide cod.
14 and 15 are product ids you can add more ids as you needed.

function is_product_in_cart( $prodids ){
$product_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
if ( in_array( $product->id, $prodids ) ) {
$product_in_cart = true;
}

}
return $product_in_cart;
}
// Disable gateway based on country
function payment_gateway_disable_product( $available_gateways ) {
global $woocommerce;
//print_r( $available_gateways );
$prodids=array(14,15);
if ( isset( $available_gateways['paypal'] ) && is_product_in_cart( $prodids ) ) {
unset( $available_gateways['paypal'] );
}else{
unset( $available_gateways['cod'] );
}
return $available_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_product' );

2016-12-05

Arnav Joy answers:

are you still looking for help ?