Skip to content

Instantly share code, notes, and snippets.

@stormwild
Last active November 5, 2023 01:40
Show Gist options
  • Star 49 You must be signed in to star a gist
  • Fork 17 You must be signed in to fork a gist
  • Save stormwild/7f914183fc18458f6ab78e055538dcf0 to your computer and use it in GitHub Desktop.
Save stormwild/7f914183fc18458f6ab78e055538dcf0 to your computer and use it in GitHub Desktop.
WooCommerce Creating Order Programmatically

WooCommerce Creating Order Programmatically

WooCommerce Create Order

creating Woocommerce order with line_item programatically

// http://stackoverflow.com/questions/26581467/creating-woocommerce-order-with-line-item-programatically
$address = array(
            'first_name' => 'Fresher',
            'last_name'  => 'StAcK OvErFloW',
            'company'    => 'stackoverflow',
            'email'      => 'test@test.com',
            'phone'      => '777-777-777-777',
            'address_1'  => '31 Main Street',
            'address_2'  => '', 
            'city'       => 'Chennai',
            'state'      => 'TN',
            'postcode'   => '12345',
            'country'    => 'IN'
        );

        $order = wc_create_order();
        $order->add_product( get_product( '12' ), 2 ); //(get_product with id and next is for quantity)
        $order->set_address( $address, 'billing' );
        $order->set_address( $address, 'shipping' );
        $order->add_coupon('Fresher','10','2'); // accepted param $couponcode, $couponamount,$coupon_tax
        $order->calculate_totals();

Wordpress (Woocommerce extension) - Create new order programatically

// http://stackoverflow.com/questions/17163251/wordpress-woocommerce-extension-create-new-order-programatically
function create_test_sub() {

    $email = 'test@test.com';

    $start_date = '2015-01-01 00:00:00';

    $address = array(
        'first_name' => 'Jeremy',
        'last_name'  => 'Test',
        'company'    => '',
        'email'      => $email,
        'phone'      => '777-777-777-777',
        'address_1'  => '31 Main Street',
        'address_2'  => '', 
        'city'       => 'Auckland',
        'state'      => 'AKL',
        'postcode'   => '12345',
        'country'    => 'AU'
    );

    $default_password = wp_generate_password();

    if (!$user = get_user_by('login', $email)) $user = wp_create_user( $email, $default_password, $email );

    // I've used one product with multiple variations

    $parent_product = wc_get_product(22998);

    $args = array(
        'attribute_billing-period' => 'Yearly',
        'attribute_subscription-type' => 'Both'
    );

    $product_variation = $parent_product->get_matching_variation($args);

    $product = wc_get_product($product_variation);  

    // Each variation also has its own shipping class

    $shipping_class = get_term_by('slug', $product->get_shipping_class(), 'product_shipping_class');

    WC()->shipping->load_shipping_methods();
    $shipping_methods = WC()->shipping->get_shipping_methods();

    // I have some logic for selecting which shipping method to use; your use case will likely be different, so figure out the method you need and store it in $selected_shipping_method

    $selected_shipping_method = $shipping_methods['free_shipping'];

    $class_cost = $selected_shipping_method->get_option('class_cost_' . $shipping_class->term_id);

    $quantity = 1;

    // As far as I can see, you need to create the order first, then the sub

    $order = wc_create_order(array('customer_id' => $user->id));

    $order->add_product( $product, $quantity, $args);
    $order->set_address( $address, 'billing' );
    $order->set_address( $address, 'shipping' );

    $order->add_shipping((object)array (
        'id' => $selected_shipping_method->id,
        'label'    => $selected_shipping_method->title,
        'cost'     => (float)$class_cost,
        'taxes'    => array(),
        'calc_tax'  => 'per_order'
    ));

    $order->calculate_totals();

    $order->update_status("completed", 'Imported order', TRUE);

    // Order created, now create sub attached to it -- optional if you're not creating a subscription, obvs

    // Each variation has a different subscription period

    $period = WC_Subscriptions_Product::get_period( $product );
    $interval = WC_Subscriptions_Product::get_interval( $product );

    $sub = wcs_create_subscription(array('order_id' => $order->id, 'billing_period' => $period, 'billing_interval' => $interval, 'start_date' => $start_date));

    $sub->add_product( $product, $quantity, $args);
    $sub->set_address( $address, 'billing' );
    $sub->set_address( $address, 'shipping' );

    $sub->add_shipping((object)array (
        'id' => $selected_shipping_method->id,
        'label'    => $selected_shipping_method->title,
        'cost'     => (float)$class_cost,
        'taxes'    => array(),
        'calc_tax'  => 'per_order'
    ));

    $sub->calculate_totals();

    WC_Subscriptions_Manager::activate_subscriptions_for_order($order);

    print "<a href='/wp-admin/post.php?post=" . $sub->id . "&action=edit'>Sub created! Click here to edit</a>";
}
@mbtocalli
Copy link

is it possible to replace the PLACE ORDER default function with this one or similar? How should I do that?

@jayyugtia
Copy link

jayyugtia commented Nov 21, 2017

How to set Subscription Action in above code?
And how to set paypal credential in subscription.

@jayyugtia
Copy link

Another things,

I have create one subscription but I can not get any email for renewal after subscription.
Please help me.

@Arsintorabi
Copy link

hello
how apply discount code to order total after order created?

@ramonfincken
Copy link

get_product is deprecated, use wc_get_product()

@zkenstein
Copy link

How to modified this to implementing external JSon data using an api url and API key?

@mategvo
Copy link

mategvo commented Mar 11, 2019

Thanks for there, nicely done!

@maartents
Copy link

how can i send someone to the payment page? after loading the function

@milardovich
Copy link

I think since newer versions of WooCommerce the add_shipping() method requires an object of type WC_Shipping_Rate.

I would replace this:

$sub->add_shipping((object)array (
        'id' => $selected_shipping_method->id,
        'label'    => $selected_shipping_method->title,
        'cost'     => (float)$class_cost,
        'taxes'    => array(),
        'calc_tax'  => 'per_order'
    ));

For this:


$shippingMethod = new \WC_Shipping_Rate($selected_shipping_method->id,$selected_shipping_method->title, (float)$class_cost);
$sub->add_shipping($shippingMethod);

Otherwise you will get the following error:

CRITICAL Uncaught Error: Call to undefined method stdClass::get_meta_data() in wp-content/plugins/woocommerce/includes/legacy/abstract-wc-legacy-order.php:85

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment