0

I am trying to create a form that allows a user to input a custom donation amount and that changes the product price automatically. I need the form outside of the "product" the form will eventually allow the user to select one of 3 products using a radio. For the life of me I can't get the form input to pass to the cart.

Here is what I have so far, just trying to get it to work on a single product:

<form method="post" enctype="multipart/form-data">
  <input type="hidden" name="add-to-cart" value="11">
  <input type="text" name="donation">
  <button type="submit">Add Donation</button>   
</form>

And some functions:

// Sanitize Data    
function donation_add_cart_item_data( $cart_item, $product_id ){
  if( isset( $_POST['donation'] ) ) {
    $cart_item['donation'] = sanitize_text_field( $_POST['donation'] );
  }

  return $cart_item;
}

add_filter( 'woocommerce_add_cart_item_data', 'donation_add_cart_item_data', 10, 2 );

// Add Data to Cart Item    
function donation_get_cart_item_from_session( $cart_item, $values ) {
 if ( isset( $values['donation'] ) ){
   $cart_item['donation'] = $values['donation'];
 }
 return $cart_item;
}

add_filter( 'woocommerce_get_cart_item_from_session', 'donation_get_cart_item_from_session', 20, 2 );


Set Custom Price for Donations Based on Form Input

function woo_add_donation( $cart_object, $values=null ) {
  if( isset( $values['donation']) ){
    foreach ( $cart_object->cart_contents as $key => $value ) {
      $value['data']->price = $values['donation'];
    }
  }
}

add_action( 'woocommerce_before_calculate_totals', 'woo_add_donation');

There must be an easier way and this doesn't work. The product is added with a final price of 0.

RiotAct
  • 743
  • 9
  • 33

1 Answers1

0

I found the answer here: Change cart item price based on custom cart data in WooCommerce

I was able to adjust this to my purposes:

add_filter( 'woocommerce_add_cart_item', 'add_custom_cart_item_data', 10, 2 );
function add_custom_cart_item_data( $cart_item_data, $cart_item_key ) {

    if( isset( $_POST['donation'] ) )
        $cart_item_data['donation'] = $_POST['donation'];

    return $cart_item_data;
}


add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_price', 10, 1 );
function set_custom_cart_item_price( $wc_cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // First loop to check if product 11 is in cart
    foreach ( $wc_cart->get_cart() as $cart_item ){
        if( ! empty($cart_item['donation']) )
            $cart_item['data']->set_price( $cart_item['donation'] );
    }
}

Works like a charm!

RiotAct
  • 743
  • 9
  • 33