:::: MENU ::::

WooCommerce Create Order Programmatically

WooCommerce Create Order Programmatically

Today we will talk about how to create order programmatically. While working on your WooCommerce Store, You need to create an order programmatically for any reason like creating a custom form for creating the order. Instead of using the WooCommerce interface to create customers or orders, explore this tutorial to do it programmatically.

/* First need address */
$orderAddress = array(
        'first_name' => 'test', //add first name to order address
        'last_name'  => 'test', //add first name to order address
        'company'    => 'test', //add company name to order address
        'email'      => 'test@test.com', //add email to order address
        'phone'      => 123456677, //add phone to order address
        'address_1'  => 'test', //add address to order address
        'address_2'  => '',
        'city'       => 'test', //add city to order address
        'state'      => 'test', //add state to order address
        'postcode'   => 'test', //add postcode to order address
        'country'    => 'US'.  //add country to order address
    );

    $cutomOrder = wc_create_order(); // create new object for order
    $productId = 20; // set product id
    $quantity  = 2;  // set product quantity
    $cutomOrder->add_product( get_product( $productId ), $quantity ); // add product and quantity to order
    $cutomOrder->set_address( $orderAddress, 'billing' ); // set billing address
    $cutomOrder->set_address( $orderAddress, 'shipping' ); // set shipping address
    $cutomOrder->calculate_totals(); // calculate total
    update_post_meta( $cutomOrder->id, '_payment_method', 'cod' ); //set payment method
    update_post_meta( $cutomOrder->id, '_payment_method_title', 'cod' ); //set payment title
Author: Qaisar Satti
Category: WooCommerce
Last Modified: January 21, 2021


Comments are closed.