在我们的Woocommercestore ,我们想给买家一个免费的礼物,每50美元花在选定的类别-下面是我们的代码在functions.php,它的工作,但还不够好.
我们现在面临的问题是,当买家花费50.50美元、51美元或52美元时,WooCommerce不会将免费礼物添加到购物车中.相反,WooCommerce只会在金额略高时才会增加,比如57美元或更多,或者当产品数量超过50美元的目标时.
该代码目前的问题是,它不踢,并添加1免费礼物时,目标花费50美元是满足
请帮帮忙
```
// Free Gift - Auto Add To Cart //
add_action('woocommerce_before_calculate_totals' , 'freegift_q12024', 10, 1);
function freegift_q12024( $cart_object ){
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$category_slug=array('categoryA', 'categoryB', 'categoryC', 'categoryD', 'categoryE', 'categoryF'); // Category slugs
$product_gifted_id=54657; // Gift Product ID
$gift_on_spent=50; // Every X Spend
$total_gift=0;
$total_gift_exits=0;
$total_sub_gift=0;
$cart_items_total = 0; // Initializing
foreach ($cart_object->get_cart() as $key => $cart_item) {
if ( has_term( $category_slug, 'product_cat', $cart_item['product_id'] ) ) {
if($cart_item['product_id']!=$product_gifted_id){
$total_sub_gift=$total_sub_gift+$cart_item['line_total'];
}
if($cart_item['product_id']=$product_gifted_id){
$total_gift_exits=$cart_item['quantity'];
}
}
}
if($total_sub_gift>0){
$total_gift=floor(($total_sub_gift/$gift_on_spent));
}
if($total_gift_exits!=$total_gift){
$product_gifted_cart_id = WC()->cart->generate_cart_id( $product_gifted_id );
$product_gifted_in_cart = WC()->cart->find_product_in_cart( $product_gifted_cart_id );
if ($product_gifted_in_cart ){ WC()->cart->remove_cart_item( $product_gifted_in_cart ); }
$product_cart_id = WC()->cart->generate_cart_id( $product_gifted_id );
if( ! WC()->cart->find_product_in_cart( $product_cart_id ) ){
if ($total_gift>0){ WC()->cart->add_to_cart( $product_gifted_id,$total_gift);}
}
}
if($total_gift>0){
foreach ($cart_object->get_cart() as $key => $cart_item) {
if($cart_item['product_id']==$product_gifted_id){
$cart_item['data']->set_price(0);
$cart_item['data']->set_regular_price(0);
}
}
}
}
// Free Gift - Disable remove from cart //
add_filter('woocommerce_cart_item_remove_link', 'freegift_q12024_noremovefromcart', 20, 2 );
function freegift_q12024_noremovefromcart( $button_link, $cart_item_key ){
//SET HERE your specific products IDs
$targeted_products_ids = array(54657);
// Get the current cart item
$cart_item = WC()->cart->get_cart()[$cart_item_key];
// If the targeted product is in cart we remove the button link
if( in_array($cart_item['data']->get_id(), $targeted_products_ids) )
$button_link = '';
return $button_link;
}
```
上面的代码起作用了-它会自动添加免费礼物,但问题是它不会自动添加到确切的50美元支出目标,需要更多的支出或物品数量才能初始化(这是问题所在)