php - 基于 Woocommerce 中的产品类别和项目计数的购物车总数
问题描述
我正在尝试将购物车总额设置为 10 英镑,当购物车中有 4 件商品并且没有一件商品属于“圣诞节”类别时。
例如
- 购物车中有 4 件商品,但圣诞节类别中有 4 件。忽略规则并遵循按项目定价。
- 购物车中有 4 件商品,但有 4 件来自非圣诞节类别。将购物车价格设置为 10 英镑。
- 购物车中有 4 件商品,但圣诞节类别中有 2 件。忽略规则并遵循按项目定价。
我已经编写了代码,目前可以将任何 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;
}
}
}
解决方案
更新:您的代码中有错误,请尝试以下操作:
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;
}
它应该更好地工作。
推荐阅读
- apache-kafka - 是否可以在分区数量上扩展消费者任务?
- git - git merge 后在 git log graph 中保留分支的提交历史
- javascript - VueJS 在页面加载时处理多个承诺
- karate - 空手道:在 json 中解析变量的奇怪问题
- email - Gmail 标记、活动预订、没有预订编号的位置名称
- apache-spark - 使用 PySpark 的 MesosSchedulerDriver 出现问题
- php - 如何用给定的数字替换模式中的 x?
- python - Python多处理 - 池中的进程数量是否会因错误而减少?
- angular - 如何为 .Net Core2.2 和 Angular7 应用程序创建一个 docker 映像?
- java - Mockito ArgumentCaptor:如何捕获类和对象