If you want to auto add or remove a freebie product from cart in your WooCommerce based online store. The following code will add a freebie product on first add to cart just once. If all other cart items are removed, the freebie item will be removed too:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | add_action( 'woocommerce_before_calculate_totals', 'add_remove_freebie', 50, 1 ); function add_remove_freebie( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return; $freebie_id = 70; // <== HERE set the freebie product ID $has_others = false; // Loop through cart items foreach( $cart->get_cart() as $cart_item_key => $cart_item ) { // Added Woocommerce compatibility version $product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id(); if( $product_id == $freebie_id ) { // Freebie is in cart $freebie_key = $cart_item_key; } else { // Other items are in cart $has_others = true; } } // If freebie product is alone in cart we remove it if( ! $has_others && isset( $freebie_key ) ){ $cart->remove_cart_item( $freebie_key ); } elseif ( $has_others && ! isset( $freebie_key ) ) { $cart->add_to_cart($freebie_id); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.