[英]Remove payment gateway if specific product is in the cart (Woocommerce)
In my Woocommerce setup, I have two payment gateways. 在我的Woocommerce设置中,我有两个付款网关。 If a specific product (id = 1187) is in the cart, I want to show
gateway_2
and hide gateway_1
. 如果购物车中有特定产品(id = 1187),我想显示
gateway_2
并隐藏gateway_1
。 If that product is NOT in the cart, then show " gateway_1
" and hide gateway_2
. 如果该产品
gateway_1
购物车中,请显示“ gateway_1
”并隐藏gateway_2
。
The code below works if I add product 1187 first. 如果我先添加产品1187,则下面的代码有效。 But, if I first add a product that is NOT "1187", then it shows
gateway_1
regardless. 但是,如果我首先添加的产品不是“ 1187”,则无论如何它都显示
gateway_1
。 How can I modify this code so that, no matter what, if ID 1187 is in the cart, then ONLY show gateway_2
? 如何修改此代码,以便无论如何如果购物车中有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;
}
The problem with your code is that you break
the loop, regardless of the condition. 代码的问题是,无论情况如何,都将
break
循环。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.