如果购物车中有特定产品,请删除支付网关(Woocommerce)


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

在我的Wooccommerce设置中,我有两个支付网关。如果购物车中有特定的产品(id=1187),我想显示gateway_2并隐藏gateway_1。如果该产品不在购物车中,则显示"gateway_1"并隐藏gateway_2

如果我先添加产品1187,下面的代码就可以工作了。但是,如果我首先添加一个不是"1187"的产品,那么不管怎样,它都会显示gateway_1。我如何修改此代码,以便无论怎样,如果ID 1187在购物车中,则仅显示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;
}

代码的问题在于,无论条件如何,都要break循环。

可能的解决方案:

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