When you aim a certain basket amount to add an advertising product to a basket, you can use woocommerce_before_calculate_totals to achieve this with a special function.
You should also remove this promo item if the client updates the cart (which is also built into this custom function).
Here is the code:
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 = 99; // <=== <=== <=== Set HERE the ID of your promotional product $targeted_cart_subtotal = 100; // <=== 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); } } }
This code continues the function.php file of your active child theme (or theme) or in any plugin file.
This code has been verified and works.
Related branch: WooCommerce - Automatically add or automatically remove product from cart
Code Updated (2017-04-19)
source share