首先,感谢您的宝贵时间。
我们有一些产品提供付款计划,其中包括130天的试用期。
当用户将产品添加到购物车中的"付款计划"类别(下面的id=41
)时,我希望购物车显示价格为$1,然后支付X次$xx.xx
。后端只需要传递产品SKU,所以这纯粹是出于显示的原因。
这段代码可以工作,但是无论购物车中有多少项都会循环。是否有办法让我在它感知到"付费计划"产品类别时立即停止循环?
代码:
<td><?php
function check_payment() {
//Check to see if user has product in cart
global $woocommerce;
//assigns a default negative value
$contains_special = false;
$wccart= WC()->cart->get_cart();
if ( !empty( $wccart ) ) {
foreach ( WC()->cart->get_cart() as $cart_item ) {
function is_item_special( $product_id ){
if( has_term( 'payment-plan', 'product_cat', $product_id ) ) {
return TRUE;
} else {
return false;
}
}//function
if ( is_item_special( $cart_item['product_id'] ) ) {
$contains_special = true;
$firstpayment = get_post_meta( $_product->id, 'firstpayment', true );
$getsubtotal = WC()->cart->get_cart_subtotal(); //get cart subtotal
$trimbefore = str_replace('<span class="amount">$', "", $getsubtotal); //$getsubtotal returns <span class="amount>XX.XX</span> this trims off the opening span tag
$intsubtotal = str_replace('</span>', "", $trimbefore); //trim closing span tag
$formatsubtotal = number_format((float)$intsubtotal, 2, '.', '');//makes an integer
$numberofpayments = get_post_meta( $_product->id, 'payments', true );
$afterfirsttotal = $formatsubtotal - 1.00;
$paymentamount = number_format((float)$afterfirsttotal, 2, '.', '') / $numberofpayments;
echo '$' . $firstpayment . '<br/> then ' . $numberofpayments . ' payments of $' . number_format((float)$paymentamount, 2, '.', '');
break;
} else {
wc_cart_totals_subtotal_html();
}//if/else statement
}//foreach loop
} //if cart isn't empty
} //function
?>
我是PHP的半新手,仍然试图理解一些事情,所以很抱歉,如果这只是显而易见的!
这是我过去使用过的一些东西(从我检查具有特定post元字段的产品时稍微修改)。从你的问题中我可以看出,你似乎在寻找break
,这是如何在满足特定条件后退出foreach循环。
第一个函数循环遍历购物车项目,寻找符合条件的任何项目。注意if ( ! empty( WC()->cart->get_cart() ) )
,它阻止代码在空购物车....上运行这就是你之前看到的foreach
错误的原因。
第二个函数检查产品的特定条件:在您的例子中,它是否分配了特定的产品类别。这可以很容易地在第一个函数中处理,但是为了可读性,我重构了它。
/*
* loop through cart looking for specific item
*/
function kia_check_cart_for_specials() {
$contains_special = false;
if ( ! empty( WC()->cart->get_cart() ) ) {
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( kia_is_item_special( $cart_item['product_id'] ) ) {
$contains_special = true;
break; // found a special item so we can quit now
}
}
}
return $contains_special;
}
/*
* check if an item has special category
* change the term/condition to suit your needs
*/
function kia_is_item_special( $product_id ){
if( has_term( 'special-category', 'product_cat', $product_id ) ) {
return TRUE;
} else {
return false;
}
}