Free Gift When the Cart Reaches an Amount
Automatically adds a free gift product to the cart once the subtotal reaches a set amount, and removes it again if the cart drops below.
Opens WPIDE on
Code
add_action( 'woocommerce_before_calculate_totals', function ( $cart ) {
$gift_id = 0; // Product ID of the free gift.
$threshold = 75; // Cart subtotal that unlocks the gift.
static $running = false;
if ( ! $gift_id || $running || ( is_admin() && ! wp_doing_ajax() ) ) {
return;
}
$running = true;
$subtotal = 0;
$gift_key = '';
foreach ( $cart->get_cart() as $key => $item ) {
if ( (int) $item['product_id'] === $gift_id ) {
$gift_key = $key;
continue;
}
$subtotal += (float) $item['data']->get_price() * (int) $item['quantity'];
}
if ( $subtotal >= $threshold && ! $gift_key ) {
$cart->add_to_cart( $gift_id, 1 );
} elseif ( $subtotal < $threshold && $gift_key ) {
$cart->remove_cart_item( $gift_key );
}
$running = false;
} );
Notes
Create the gift as a product priced at 0 (it can be hidden from the catalog), then set $gift_id and $threshold.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.