Caronlab Australia
Caronlab Australia

Reputation: 51

Create woocommerce order with gravity forms metadata

I have a interesting and bit complicated task to do with gravity forms and Woocommerce.

On our website, we offer free sample to every new customer registered. We tried to build something like as soon as new user fill their details like email, name and address as well as the free sample they want to get and submit, it should create an order in Woocommerce. Is it possible with gravity forms or its not possible at all?

I tried myself, it didn't work for me.

Upvotes: 1

Views: 2029

Answers (1)

Ali_k
Ali_k

Reputation: 1661

It's possible, but there are a lot of variables that need to be taken into consideration, so it's really hard to help without you doing an attempt first.

This will only show you where to start, you need to figure out the rest:

add_action( 'gform_after_submission', 'post_to_third_party', 10, 2 );
function post_to_third_party( $entry, $form ) {
    global $woocommerce;
    // use this to find out $entry output
    var_dump($entry);

    // Make sure to add hidden field somewhere in the form with product id and define it here, If you have some other way of defining products in the form you need to make sure product id is returned in the variable below somehow
    $product_id = rgar( $entry, '12' );



    $address = array(
      'first_name' => rgar( $entry, '5' ),
      'last_name'  => rgar( $entry, '2' ),
      'company'    => rgar( $entry, '3' ),
      'email'      => rgar( $entry, '4' ),
      'phone'      => rgar( $entry, '5' ),
      'address_1'  => rgar( $entry, '6' ),
      'address_2'  => rgar( $entry, '7' ),
      'city'       => rgar( $entry, '8' ),
      'state'      => rgar( $entry, '9' ),
      'postcode'   => rgar( $entry, '10' ),
      'country'    => rgar( $entry, '11' ),
    );

    $prices = array( 'totals' => array( 
            'subtotal' => 0, 
            'total' => 0,
        ) );

    $order = wc_create_order();

    $order->add_product( wc_get_product($product_id), 1, $prices); 
    $order->set_address( $address, 'billing' );
    $order->calculate_totals();
    $order->update_status("processing", 'Sample Order', TRUE);  


}

Upvotes: 3

Related Questions