I am trying to add a free product to the cart if the order total is above $199.99
I have achieved this and it is working. The issue is that I need to remove the product if the user then deletes an item from the cart and goes below $199.99 again (to prevent gaming the system).
What I have seems to be working. The problem is that it seems I need to click 2 links before the REMOVE FROM CART action seems to be working (or refresh the page).
What is causing this? Can the remove action be accomplished with AJAX by any chance?
// -------------------------------------------
// ADD PRODUCT IF ORDER MINIMUM ABOVE 200
/*
* Automatically adding the product to the cart when cart total amount reach to $199.99.
*/
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 199.99;
if ( $woocommerce->cart->total >= $cart_total ) {
if ( is_user_logged_in() ) {
$free_product_id = 339; // Product Id of the free product which will get added to cart
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id );
}
}
}
if ( $woocommerce->cart->total <= $cart_total && $found ) {
WC()->cart->remove_cart_item( $free_product_id );
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
add_action( 'template_redirect', 'remove_product_from_cart_programmatically' );
function remove_product_from_cart_programmatically() {
if ( is_admin() ) return;
$product_id = 339; // product id
$cart_total = 199.99;
$in_cart = false;
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['product_id'] === $product_id ) {
$in_cart = true;
$key = $cart_item_key;
break;
}
}
if( WC()->cart->total < $cart_total ) {
if ( $in_cart ) WC()->cart->remove_cart_item( $key );
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…