title: Woocommerce: Programmatically Update Item In Cart
body: <p>I need to programmatically and dynamically change the price of an item in the cart.</p>
  
  <p>I’ve tried varying combinations of Woocommerce action hooks, the cart and session objects, but nothing quite seems to do the trick. I thought this wouldn’t be so challenging.</p>
  
  <pre><code>add_action( 'woocommerce_before_calculate_totals', 'change_cart_item_price' );
  
  function change_cart_item_price( $cart_object ) {
  
      foreach ( $cart_object-&gt;cart_contents as $key =&gt; $value ) {
  
          if( 123 == $value['data']-&gt;id ) {
  
              $new_price = function_to_get_new_price( $value, get_current_user_id( ) );
              $value['data']-&gt;price = $new_price;
          }
     }
  }
  </code></pre>
  
  <p>The above code changes the price for each item only on the checkout page, or when updating the cart (<em>ie: the hook is called when removing an item from the cart</em>), but not indefinitely. </p>
  
  <p>I'm using the Woocommerce Gravity Forms add-on. I have one product in particular, which will be ordered multiple times by a given user. The user will be allowed 5x free with only shipping fees, and each above 5 will be $20. I have this much coded and functional with Gravity Forms hooks that dynamically populate fields. Shipping is specific to fields within the gravity form, therefore I am leaving that calculation to Gravity Forms.</p>
  
  <p>My issue is that if a user reduces the quantity of this product from their order (removes one of the items from the cart), it should re-calculate the price of each item of the same product within the cart, otherwise they could be over-charged (<em>an item that used to be the 6th is now the 4th, but the price remains the same, which it shouldn't</em>)</p>
  
  <p><em>Therefore</em>, I would like to re-calculate the price of each item in the cart, based on the quantity of this particular product, every time something is removed from the cart.</p>
  
  <p>--- EDIT ---</p>
  
  <p>The above code works, but I'm realizing the issue must be a custom loop I'm using to display the prices...</p>
  
  <pre><code>foreach ( WC()-&gt;cart-&gt;get_cart() as $cart_item_key =&gt; $cart_item ) {
      $_product = $cart_item['data'];
      if( 123 == $_product-&gt;post-&gt;ID ) {
          $price_not_updated = $cart_item['data']-&gt;price;
      }
  }
  </code></pre>