在订单创建中以编程方式添加自定义订单项元



我尝试了很多不同的代码,但没有任何帮助。我调用自定义钩子自定义函数从自定义事件创建一个订单与现有的产品,但自定义产品元在订单项目行。

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);

您可以通过使用woocommerce_add_order_item_metaadd_meta_data来完成此操作。

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();
}

最新更新