【发布时间】:2020-11-24 04:57:14
【问题描述】:
我正在尝试对购物车实施自定义折扣规则。基本上有 WooCommerce,该网站正在销售 T 恤。目前有一项促销活动,如果您购买 3 件 T 恤,您只需支付 2 件,而价格最低的一件则免费。
我使用钩子 woocommerce_cart_calculate_fees 创建了一个自定义函数,到目前为止它正在工作。
这是我的代码:
add_action( 'woocommerce_cart_calculate_fees', 'iom_add_custom_discount', 10, 1 );
function iom_add_custom_discount( $wc_cart ){
$discount = 0;
$product_ids = array();
$item_prices = array();
$in_cart = true;
foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_product = $cart_item['data'];
if ( has_term( 'detski-bodita', 'product_cat', $cart_product->get_id() ) ) {
$in_cart = true;
}else {
$product_ids[] = $cart_product->get_id();
$item_prices[$cart_product->get_id()] = $cart_product->get_price();
}
}
if( $in_cart ) {
$count_ids = count($product_ids);
asort( $item_prices ); //Sort the prices from lowest to highest
$count = 0;
if( $count_ids == 3 ) {
foreach( $item_prices as $id => $price ) {
if( $count >= 1 ) {
break;
}
//$product = wc_get_product( $id );
//$price = $product->get_price();
$discount -= ($price * 100) / 100;
$count++;
}
}
}
if( $discount != 0 ){
$wc_cart->add_fee( 'Отстъпка', $discount, true );
# Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
}
显示并应用折扣。但是,它似乎只有当我在购物车中有 3 种不同的产品时才有效。如果我有 1 个数量为 2 的产品和 1 个数量为 1 的产品,则它不起作用。
如何调整函数以使其适用于项目数量计数?
这是购物车页面的截图:
编辑:
折扣中的产品类别说明:
只有当购物车中有 3 件属于同一类别的商品时,才能享受折扣。
例如,类别是 T 恤和连帽衫。如果我的购物车中有 3 件 T 恤,则应享受折扣。如果我有 2 件 T 恤和 1 件连帽衫,则不应享受折扣。
【问题讨论】:
-
我不知道。感谢您编辑帖子。 :)
-
是的,这就是我需要帮助的原因。 :) 我更偏向于“前端”,但我对 php 的使用仍然不是很好。
标签: php wordpress woocommerce hook-woocommerce discount