Search code examples
phpwordpresswoocommerceorderswoocommerce-bookings

WooCommerce Bookings: Create a Booking Order programmatically


I have been trying this for a couple of hours now, with different code & reading every doc on booking I can find - but I seem to be unable to figure out how exactly I do this.

My biggest inspiration comes from the WooCommerce Booking Doc, but this just adds a follow-up booking to an existing order. But how do I go about doing it from scratch?

I tried the following, but cant really get it to work.

  1. I generate a new order with:

    $address = array(
        'first_name' => 'TestFirst',
        'last_name'  => 'TestLast',
        'company'    => 'Overflow',
        'email'      => '[email protected]',
        'phone'      => '777-777-777-777',
        'address_1'  => '35 Main Street',
        'address_2'  => '', 
        'city'       => 'Net York',
        'state'      => 'NY',
        'postcode'   => '2323',
        'country'    => 'US'
    
    $order = wc_create_order();
    $order->set_address( $address, 'billing' );
    $order->set_address( $address, 'shipping' );
    
  2. I create a booking by

    $new_booking_data = array(
            'start_date'  => strtotime( '+1 week', $prev_booking->start ), // same time, 1 week on
            'end_date'    => strtotime( '+1 week', $prev_booking->end ), // same time, 1 week on
            'resource_id' => $prev_booking->resource_id, // same resource
            'parent_id'   => $booking_id
    )
    create_wc_booking( $product_id, $new_booking_data = array(), $status =     'confirmed', $exact = false )
    
  3. And here I'm stuck, what do I have to do now? I figure I have to connect the booking ID with the order from 1. - but I'm not really sure how.

What I am doing wrong?

Thanks.


Solution

  • In your code you are defining this array first (with a missing ; at the end of the array).

    Then instead of using $new_booking_data defined variable simply in your function create_wc_booking(), you are assigning to it an empty array, that NULLs the code above. So you have to set it just like this:

    // Defined array variable
    $new_booking_data = array(
            'start_date'  => strtotime( '+1 week', $prev_booking->start ), // same time, 1 week on
            'end_date'    => strtotime( '+1 week', $prev_booking->end ), // same time, 1 week on
            'resource_id' => $prev_booking->resource_id, // same resource
            'parent_id'   => $booking_id
    ); // <= Missing ";" HERE
    
    // Define this variables outside your function
    $status = 'confirmed';
    $exact = false;
    
    // Now you just put your variables simply like this
    create_wc_booking( $product_id, $new_booking_data, $status, $exact );
    

    Or you can put the values too, this way:

    create_wc_booking( $product_id, $new_booking_data, 'confirmed', false );
    

    This should better work now… I hope.