当购物车中有4件物品,但都不属于“圣诞节”类别时,我想将购物车总额设为10英镑。
例如
我已经编写了当前可将任意4个购物车商品设置为10英镑的代码:
add_filter( 'woocommerce_calculated_total', 'calculated_total', 10, 2 );
function calculated_total( $total, $cart ) {
$taster_item_count = 4;
if ( $cart->cart_contents_count == $taster_item_count ) {
return 10;
}
return $total;
}
但是,当我尝试添加条件类别时,它不遵循规则吗?:
add_filter( 'woocommerce_calculated_total', 'calculated_total', 10, 2 );
// check each cart item for category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
// ONLY EXECUTE BELOW FUNCTION IF DOESN'T CONTAIN CHRISTMAS CATEGORY
if ( !has_term( 'christmas', 'product_cat', $product->id ) ) {
function calculated_total( $total, $cart ) {
$taster_item_count = 4;
if ( $cart->cart_contents_count == $taster_item_count ) {
return 10;
}
return $total;
}
}
}
答案 0 :(得分:1)
更新:您的代码中有错误,请尝试以下操作:
add_filter( 'woocommerce_calculated_total', 'calculated_total', 10, 2 );
function calculated_total( $total, $cart ) {
$taster_count = 4;
$item_count = $cart->get_cart_contents_count();
$chistm_count = 0;
foreach ( $cart->get_cart() as $cart_item ) {
if ( ! has_term( 'christmas', 'product_cat', $cart_item['product_id'] ) ) {
$chistm_count += $cart_item['quantity'];
}
}
if( $taster_count == $item_count && $chistm_count == $taster_count ) {
$total = 10;
}
return $total;
}
应该更好地工作。