I understand you’re looking at creating an order, but the following concept is the same.
If you adjust inventory by editing a product in WooCommerce you have no record of changes. This code is for a simple inventory management form that provides that trail. It is in a Snippet using Code Snippets.
// INVENTORY ADDITION
add_filter( 'gform_confirmation_1', 'inventory_management', 10, 3 );
function inventory_management( $confirmation, $form, $entry ) {
$user_id = rgar( $entry, "3");
$user_email = rgar( $entry, "19");
$woo_id = rgar( $entry, "5");
$parent_id = rgar( $entry, "20");
$woo_description = rgar( $entry, "13");
$inventory_current = intval(rgar( $entry, "14"));
$inventory_addition = intval(rgar( $entry, "17"));
$inventory_new = intval(rgar( $entry, "18"));
if ($parent_id == 0) {
$api_url = "https://*****SITEURL*****/wp-json/wc/v3/products/".$woo_id;
$redirect_url = array( 'redirect' => '/wp-admin/post.php?post='.$woo_id.'&action=edit' );
} else {
$api_url = "https://*****SITEURL*****/wp-json/wc/v3/products/".$parent_id."/variations/".$woo_id;
$redirect_url = array( 'redirect' => '/wp-admin/post.php?post='.$parent_id.'&action=edit' );
}
$redirect_url = array( 'redirect' => '/inventory-management/' );
// UPDATE INVENTORY IN WOOCOMMERCE
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $api_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS =>'{"stock_quantity":"'.$inventory_new.'"}',
CURLOPT_HTTPHEADER => array(
'Authorization: Basic '. base64_encode("KEY:SECRET"),
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
curl_close($curl);
$confirmation = $redirect_url;
return $confirmation;
}
Best reference is Woo Rest API.
You’ll need to create an API Key in WooCommerce on your site and place them in 'Authorization: Basic '. base64_encode(“KEY:SECRET”),
If a product has a parent_id, that means it’s a variation, otherwise it is the parent (a simple product) and this makes a difference in what URL is used. This could impact you if you intend on including products and line items in your Order creation.
Since I’m only updating the one value, “stock_quantity”, I didn’t build a JSON array which you would need to do and place in CURLOPT_POSTFIELDS.
Let me know of any questions.