在我的Woocommerce设置中,我有两个支付网关。如果购物车中有特定产品(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;
}
答案 0 :(得分:0)
代码的问题在于,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;