2014-09-27 97 views
0

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

下面的代码工作,如果我先添加产品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

您的代码的问题在于,您无论条件如何,都会回环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; 
+0

谢谢!我试过这段代码,但是它产生了下面的错误:“致命错误:无法打破/继续300行的1级”,这是第一个'break'。 – LBF 2014-09-28 02:45:05

+0

对不起,'if'中的中断应该被删除(并且可选地添加到'foreach'中的'if'中。 – 2014-09-28 15:32:02

相关问题