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.