I want to give customers with orders above $50 a free gift. Not if a specific product is in the cart (there are some examples here on stackoverflow and below).
After some research I found the following code to add a free product if another specific product is added to the cart.
add_action( 'template_redirect', 'bbloomer_add_gift_if_id_in_cart' );
function bbloomer_add_gift_if_id_in_cart() {
if ( is_admin() ) return;
if ( WC()->cart->is_empty() ) return;
$product_bought_id = 32;
$product_gifted_id = 57;
// see if product id in cart
$product_bought_cart_id = WC()->cart->generate_cart_id( $product_bought_id );
$product_bought_in_cart = WC()->cart->find_product_in_cart( $product_bought_cart_id );
// see if gift id in cart
$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 not in cart remove gift, else add gift
if ( ! $product_bought_in_cart ) {
if ( $product_gifted_in_cart ) WC()->cart->remove_cart_item( $product_gifted_in_cart );
} else {
if ( ! $product_gifted_in_cart ) WC()->cart->add_to_cart( $product_gifted_id );
}
}
Found here: https://www.businessbloomer.com/woocommerce-buy-1-product-add-free-product-cart-programmatically/
I also tried this code but it doesn't update if the cart changes:
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 50;
if ( $woocommerce->cart->total >= $cart_total ) {
if ( ! is_admin() ) {
$free_product_id = 12989; // 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 );
}
}
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
Is there any way to change that code to work with any product and limit only to the cart total?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…