1 回答
TA贡献1860条经验 获得超8个赞
您不应该使用template_redirect钩子根据购物车的总阈值添加或删除免费产品……此外,您的代码有点过时并存在一些错误。
而是使用woocommerce_before_calculate_totals启用 Ajax 的钩子,这样:
add_action( 'woocommerce_before_calculate_totals', 'add_or_remove_cart_items', 10, 1 );
function add_or_remove_cart_items( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// ONLY for logged users (and avoiding the hook repetition)
if ( ! is_user_logged_in() && did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$threshold_amount = 200; // The threshold amount for cart total
$free_product_id = 339; // ID of the free product
$cart_items_total = 0; // Initializing
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
// Check if the free product is in cart
if ( $cart_item['data']->get_id() == $free_product_id ) {
$free_item_key = $cart_item_key;
}
// Get cart subtotal incl. tax from items (with discounts if any)
$cart_items_total += $cart_item['line_total'] + $cart_item['line_tax'];
}
// If Cart total is up to the defined amount and if the free products is not in cart, we add it.
if ( $cart_items_total >= $threshold_amount && ! isset($free_item_key) ) {
$cart->add_to_cart( $free_product_id );
}
// If cart total is below the defined amount and free product is in cart, we remove it.
elseif ( $cart_items_total < $threshold_amount && isset($free_item_key) ) {
$cart->remove_cart_item( $free_item_key );
}
}
代码在您的活动子主题(或活动主题)的functions.php 文件中。测试和工作。
- 1 回答
- 0 关注
- 112 浏览
添加回答
举报