Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.