I am trying to add a bookable product programmatically and have some struggles in the end.
I am using a custom booking detail page from which I want customers to directly book. My approach started out from this: Add to cart bookable product by URL - WooCommerce Bookings
The product does get added to the cart with the listed code, but I do need to add metadata, since the cart shows an error, that duration is missing and cannot be 0.
<form class="cart" method="post" enctype="multipart/form-data">
<input type="hidden" name="add-to-cart" value="product_id" class="wc-booking-product-id" />
<input type="hidden" name="start-date" value="start_date">
<input type="hidden" name="end-date" value="end_date">
<input type="hidden" name="persons" value="1">
<input type="submit" name="book" class="check_btn" value="Buy">';
</form>
With this php:
if(isset($_POST['book'])){
global $woocommerce;
$woocommerce->cart->add_to_cart( $product_id );
}
do_action( 'woocommerce_after_add_to_cart_form' );
I am sure there are better solutions to this, since this seems to be a workaround that might leave other issues. Additionally I'd like to add some more metadata to the item before adding it to the cart.
I had to change the form a bit in order to put the product into the cart as follows:
<form class="cart" method="post" enctype="multipart/form-data">
<input type="hidden" name="add-to-cart" value="'.$product_id.'" class="wc-booking-product-id" />
<input type="hidden" name="wc_bookings_field_duration" value="'.$lesson_days.'">
<input type="hidden" name="wc_bookings_field_persons" value="'.$participant_nums.'">
<input type="hidden" name="wc_bookings_field_start_date_day" value="'.$lesson_start_date->format('d').'">
<input type="hidden" name="wc_bookings_field_start_date_month" value="'.$lesson_start_date->format('m').'">
<input type="hidden" name="wc_bookings_field_start_date_year" value="'.$lesson_start_date->format('Y').'">
<input type="hidden" name="wc_bookings_field_start_date_time" value="'.$start_time.'">
<input type="submit" class="wc-bookings-booking-form-button single_add_to_cart_button button alt" value="Buy">
The main difficulty was knowing that the start date needs year, month, day, and time seperately.
One thing is still bothering me, the setting the cart price according to some internal calculations does not work yet.