我已经尝试解决这个问题有一段时间了,但似乎无法弄清楚为什么这只能以一种方式起作用。
目标:当“服务”类别在购物车中时,默认购物车总押金为 50 美元,如果购物车中没有“服务”类别的产品,则正常结帐。
问题:woocommerce 通知工作正常,但购物车没有改变。我试图从 if 语句而不是 woocommerce 通知中调用 change_calculcated_total 函数,但是无论购物车中的类别是什么,该函数始终运行...
是结构错误吗?
add_action( 'woocommerce_before_cart','bbloomer_check_category_in_cart' );
$cat_in_cart = false; // Set $cat_in_cart to false
function bbloomer_check_category_in_cart() {
// Loop through all products in the Cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// If Cart has category "services",set $cat_in_cart to true
if ( has_term( 'services','product_cat',$cart_item['product_id'] ) ) {
$cat_in_cart = true;
break;
}
}
// Do something if category "services" is in the Cart
if ( $cat_in_cart ) {
// For example,print a notice
wc_print_notice( 'Services selected,Only $50 deposit is required.','notice' );
}
}
//change cart total.
function change_calculated_total( $total,$cart ) {
if ( $cat_in_cart ){
return 50;
}else{
return $total;
}
}
add_filter( 'woocommerce_calculated_total','change_calculated_total',10,2 );