我想根据WooCommerce中的购物车金额添加特定的免费礼物。
- 80以下无产品赠品
- 80以上120以下加赠1份
- 120多加赠1赠2
基于WooCommerce答案代码中的最小购物车金额添加免费礼品产品,如果我添加1个元素,它会工作,但如果我添加礼物2,它会停止工作。
其他问题:
1.刷新购物车时,礼品1和礼品2的产品数量增加到2、3、4等,而不是保持为1,并且不更改小计。
1.显示的礼品小计不等于零
这是我的代码尝试:
function action_woocommerce_before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) {
return;
}
// Free product productIDs
$free_product_id_1 = gift1;
$free_product_id_2 = gift2;
// Minimum subtotal needed for free products
$min_subtotal_free_product_1 = 80;
$min_subtotal_free_product_2 = 120;
// Initializing
$cart_subtotal = 0;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// When free product is is cart
if ( $free_product_id_1 == $cart_item['gift1'] ) {
$free_key_1 = $cart_item_key;
$free_qty_1 = $cart_item['1'];
// Optionally set the price to zero
$cart_item['6215']->set_price( 0 );
} elseif ( $free_product_id_2 == $cart_item['gift2'] ) {
$free_key_2 = $cart_item_key;
$free_qty_2 = $cart_item['1'];
// Optionally set the price to zero
$cart_item['7912']->set_price( 0 );
} else {
// NOT empty
if ( ! empty( $cart_item['line_total'] ) ) {
$cart_subtotal += $cart_item['line_total'];
}
// NOT empty
if ( ! empty( $cart_item['line_tax'] ) ) {
$cart_subtotal += $cart_item['line_tax'];
}
}
}
// If subtotal is less than first subtotal
if ( $cart_subtotal < $min_subtotal_free_product_1 ) {
// Free product 1 is already in cart, remove it
if ( isset( $free_key_1 ) ) {
$cart->remove_cart_item( $free_key_1 );
}
// Free product 2 is already in cart, remove it
if ( isset( $free_key_2 ) ) {
$cart->remove_cart_item( $free_key_2 );
}
}
// If subtotal is between first and second subtotal
elseif ( $cart_subtotal >= $min_subtotal_free_product_1 && $cart_subtotal < $min_subtotal_free_product_2 ) {
// Free product 1 is not already in cart, add it
if ( ! isset( $free_key_1 ) ) {
$cart->add_to_cart( $free_product_id_1 );
}
// Free product 2 is in cart, remove it
if ( isset( $free_key_2 ) ) {
$cart->remove_cart_item( $free_key_2 );
}
}
// If subtotal greater than or equal to second subtotal
elseif ( $cart_subtotal > $min_subtotal_free_product_2 ) {
// Free product 1 is already in cart, remove it
if ( isset( $free_key_1 ) ) {
$cart->remove_cart_item( $free_key_1 );
}
// Free product 2 is not already in cart, add it
if ( ! isset( $free_key_2 ) ) {
$cart->add_to_cart( $free_product_id_2 );
}
}
// Keep free product 1 quantity to 1.
if ( isset( $free_qty_1 ) && $free_qty_1 > 1 ) {
$cart->set_quantity( $free_key_1, 1 );
}
// Keep free product 2 quantity to 1.
if ( isset( $free_qty_2 ) && $free_qty_2 > 1 ) {
$cart->set_quantity( $free_key_2, 1 );
}
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
谢啦,谢啦
1条答案
按热度按时间vlju58qv1#
我以这种方式修改代码,但keep不起作用: