简体   繁体   中英

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

In my Woocommerce setup, I have two payment gateways. If a specific product (id = 1187) 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 .

The code below works if I add product 1187 first. But, if I first add a product that is NOT "1187", then it shows gateway_1 regardless. How can I modify this code so that, no matter what, if ID 1187 is in the cart, then ONLY show gateway_2 ?

add_filter('woocommerce_available_payment_gateways','filter_gateways',1);

function filter_gateways($gateways){
global $woocommerce;

foreach ($woocommerce->cart->cart_contents as $key => $values ) {

//store product id's in array
$specialItem = array(1187);         

if(in_array($values['product_id'],$specialItem)){   
      unset($gateways['gateway_1']);
      break;
}
else {
    unset($gateways['gateway_2']);
    break;
}

}
return $gateways;
}

The problem with your code is that you break the loop, regardless of the condition.

Possible fix:

$inarray = false;
$specialItem = array(1187);
foreach ($woocommerce->cart->cart_contents as $key => $values ) {//enumerate over all cart contents
    if(in_array($values['product_id'],$specialItem)){//if special item is in it
        $inarray = true;//set inarray to true
        break;//optional, but will improve speed.
    }
}

if($inarray) {//product is in the cart
      unset($gateways['gateway_1']);
} else {//otherwise
    unset($gateways['gateway_2']);
}
return $gateways;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM