Add a product to cart automatically when you spend certain amount woocommerce

Hi guys, hopefully somebody can help me, really appreciated.

I’ve got a piece of PHP code that works really well in adding a product to cart when the cart total reaches £20, however, I’d then like this product removed and a new product in it’s place when the cart reaches £40, is this possible? Code below

[php]add_action( ‘woocommerce_before_calculate_totals’, ‘adding_promotional_product’, 10, 1 );
function adding_promotional_product( $cart_object ) {

if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

$promo_id = 12832; // <=== <=== <=== Set HERE the ID of your promotional product
$targeted_cart_subtotal = 16.67; // <=== Set HERE the target cart subtotal
$has_promo = false;
$subtotal = 0;

if ( !$cart_object->is_empty() ){

    // Iterating through each item in cart
    foreach ($cart_object->get_cart() as $item_key => $item_values ){

        // If Promo product is in cart
        if( $item_values['data']->id == $promo_id ) {
            $has_promo = true;
            $promo_key= $item_key;
        } else {
            // Adding subtotal item to global subtotal
            $subtotal += $item_values['line_subtotal'];
        }
    }
    // If Promo product is NOT in cart and target subtotal reached, we add it.
    if( !$has_promo && $subtotal >= $targeted_cart_subtotal ) {
        $cart_object->add_to_cart($promo_id);
        echo 'add';
    // If Promo product is in cart and target subtotal is not reached, we remove it.
    } elseif( $has_promo && $subtotal < $targeted_cart_subtotal ) {
        $cart_object->remove_cart_item($promo_key);
    }
}

}[/php]

Just add another if else statement on to what you currently have.

Sponsor our Newsletter | Privacy Policy | Terms of Service