I tried a lot of different codes, but nothing help. Im calling a custom hook with custom function from custom event to create an order with existing product but with custom product meta in order item line.
function create_order($product_id, $customer_phone, $customer_email, $customer_name, $extra_service_id, $extra_service_name) {
$args = array(
'Service ID' => $extra_service_id,
'Service Name' => $extra_service_name
);
$quantity = 1;
$product = wc_get_product($product_id);
$order = wc_create_order();
$order->add_product( $product, $quantity, $args);
$address = array(
'first_name' => $customer_name,
'email' => $customer_email,
'phone' => $customer_phone
);
$order->set_address( $address, 'billing' );
$order->set_status( 'wc-on-hold', 'Made in back-end' );
$order->calculate_totals();
$order->save();
}
add_action('create_order_hook', 'create_order', 10, 6);
CodePudding user response:
You can do this by using woocommerce_add_order_item_meta
or add_meta_data
. I added both ways.
add_action('create_order_hook', 'create_order', 10, 6);
function create_order($product_id, $customer_phone, $customer_email, $customer_name, $extra_service_id, $extra_service_name) {
$args = array(
'Service ID' => $extra_service_id,
'Service Name' => $extra_service_name
);
$quantity = 1;
$product = wc_get_product( $product_id );
$order = wc_create_order();
$order->add_product( $product, $quantity, $args);
woocommerce_add_order_item_meta( $product_id, 'custom_key', 'custom value' );
foreach ( $order->get_items() as $item_key => $item ) {
$item->add_meta_data( 'custom_key', 'custom value', true );
}
$address = array(
'first_name' => $customer_name,
'email' => $customer_email,
'phone' => $customer_phone
);
$order->set_address( $address, 'billing' );
$order->set_status( 'wc-on-hold', 'Made in back-end' );
$order->calculate_totals();
$order->save();
}