title: Woocommerce: custom price based on user input
body: <p>I did not want to post here but I could not find the answer I was looking for and I do not have enough reputation to comment on other VERY SIMILAR questions to get my exact answer.</p>
  
  <p>I found an almost perfect answer from this post: <a href="https://stackoverflow.com/questions/12327251/woocommerce-add-product-to-cart-with-price-override">WooCommerce: Add product to cart with price override?</a></p>
  
  <p>using the code:</p>
  
  <pre><code>add_action( 'woocommerce_before_calculate_totals', 'add_custom_price');
  
  function add_custom_price( $cart_object ) {
        $custom_price = 10; // This will be your custome price  
        foreach ( $cart_object-&gt;cart_contents as $key =&gt; $value ) {
            $value['data']-&gt;price = $custom_price;
        }
   }
  </code></pre>
  
  <p>and it works great...if you set a hard coded custom price.</p>
  
  <p><strong><em>My question is: How can I set a custom price based on user input?</em></strong> </p>
  
  <p>I have tried every way I can think of to pass information (I even tried using cookies, globals, sessions) and none of them worked how I wanted and all of them were, at BEST, hacks.</p>
  
  <p>The specific product in question is a donation and the customer wants the user to be able to set the donation price (rather than just creating a variable product with set price points).</p>
  
  <p>On the donation page when the user submits the donation form I am adding the donation product to the cart like so:</p>
  
  <pre><code>$donation_success = $woocommerce-&gt;cart-&gt;add_to_cart($donation_id); 
  </code></pre>
  
  <p>My donation product has a set price of 0.00 so when it is added to the cart it has a price of 0.00 (I don't know if the price is set at this point or later)</p>
  
  <p>I have tried passing in information at this point using the last variable in the add_to_cart method which accepts an array of arguments but I couldn't seem to get that to work either.</p>
  
  <p>I am sure the answer is simple but I have been trying for hours to do this right and I cannot get it to work. I am out of ideas. </p>
  
  <p>The actual code I am using at the moment is slightly different than was suggested by the answerer of the above post but works basically the same:</p>
  
  <pre><code>add_action( 'woocommerce_before_calculate_totals', 'woo_add_donation');
  
  function woo_add_donation() {
      global $woocommerce;
  
      $donation = 10;
      foreach ( WC()-&gt;cart-&gt;get_cart() as $cart_item_key =&gt; $cart_item ) {
          if($cart_item['data']-&gt;id == 358 || $cart_item['data']-&gt;id == 360){
              $cart_item['data']-&gt;set_price($donation);
          }
      }
  }
  </code></pre>
  
  <p>Thanks in advance for any helpful advice!</p>