title: Add or remove specific cart Item based on WooCommerce cart total
body: <p>I am trying to add a free product to the cart if the order total is above $199.99</p>
  
  <p>I have achieved this and it is working. The issue is that I need to remove the product if the user then deletes an item from the cart and goes below $199.99 again (to prevent gaming the system).</p>
  
  <p>What I have seems to be working. The problem is that it seems I need to click 2 links before the REMOVE FROM CART action seems to be working (or refresh the page).</p>
  
  <p>What is causing this? Can the remove action be accomplished with AJAX by any chance?</p>
  
  <pre><code>// -------------------------------------------
  // ADD PRODUCT IF ORDER MINIMUM ABOVE 200
  
  /*
  * Automatically adding the product to the cart when cart total amount reach to $199.99.
  */
  
  function aapc_add_product_to_cart() {
      global $woocommerce;
  
      $cart_total = 199.99;   
  
      if ( $woocommerce-&gt;cart-&gt;total &gt;= $cart_total ) {
          if ( is_user_logged_in() ) {
              $free_product_id = 339;  // Product Id of the free product which will get added to cart
              $found      = false;
  
              //check if product already in cart
              if ( sizeof( WC()-&gt;cart-&gt;get_cart() ) &gt; 0 ) {
                  foreach ( WC()-&gt;cart-&gt;get_cart() as $cart_item_key =&gt; $values ) {
                      $_product = $values['data'];
                      if ( $_product-&gt;get_id() == $free_product_id )
                          $found = true;                  
                  }
                  // if product not found, add it
                  if ( ! $found )
                      WC()-&gt;cart-&gt;add_to_cart( $free_product_id );
              } else {
                  // if no products in cart, add it
                  WC()-&gt;cart-&gt;add_to_cart( $free_product_id );
              }        
          }
      }
      if ( $woocommerce-&gt;cart-&gt;total &lt;= $cart_total &amp;&amp; $found ) {
                  WC()-&gt;cart-&gt;remove_cart_item( $free_product_id );
              }       
  }
  
  add_action( 'template_redirect', 'aapc_add_product_to_cart' );
  
  add_action( 'template_redirect', 'remove_product_from_cart_programmatically' );
  
  function remove_product_from_cart_programmatically() {
      if ( is_admin() ) return;
      $product_id = 339; // product id
      $cart_total = 199.99;
      $in_cart = false;
      foreach( WC()-&gt;cart-&gt;get_cart() as $cart_item_key =&gt; $cart_item ) {
          if ( $cart_item['product_id'] === $product_id ) {
              $in_cart = true;
              $key = $cart_item_key;
              break;
          }
      }
      if( WC()-&gt;cart-&gt;total &lt; $cart_total ) {
          if ( $in_cart ) WC()-&gt;cart-&gt;remove_cart_item( $key );
      }
  }
  </code></pre>