我正在为 WooCommerce 订单创建克隆功能。 我想要的是确保正确克隆产品项元数据。
/**
* Get the original order items to be clone
* Each product inside the new order must also contain the meta_data
*/
$order = wc_get_order($post_id);
$new_order = wc_get_order($new_post_id);
foreach ($order->get_items() as $item_id => $item) {
$product_id = $item->get_product_id();
$quantity = $item->get_quantity();
// Get product's meta data values
$_wwp_wholesale_priced = get_post_meta( $product_id, '_wwp_wholesale_priced', true);
$_wwp_wholesale_role = get_post_meta( $product_id, '_wwp_wholesale_role', true);
$_amount_requested = get_post_meta( $product_id, '_amount_requested', true);
$_amount_colli = get_post_meta( $product_id, '_amount_colli', true);
$args = array(
'_wwp_wholesale_priced' => $_wwp_wholesale_priced,
'_wwp_wholesale_role' => $_wwp_wholesale_role,
'_amount_requested' => $_amount_requested,
'_amount_colli' => $_amount_colli,
);
$new_order->add_product(wc_get_product($product_id), $quantity, $args);
}
在文档中,似乎传递
$args
应该可以解决问题,但我没有看到任何元数据被传递。我也尝试过使用 $item->add_meta_data
和 $item->update_meta_data
但它们似乎不起作用。我错过了什么?
您的代码中存在一些错误和遗漏的内容,请尝试以下操作:
/**
* Get the original order items to be clone
* Each product inside the new order must also contain the meta_data
*/
$order = wc_get_order($post_id);
$new_order = wc_get_order($new_post_id);
foreach ($order->get_items() as $item) {
$product = $item->get_product(); // get an instance of the WC_Product Object
$new_item_id = $new_order->add_product($product, $item->get_quantity()); // Add the product
$new_item = $new_order->get_item( $new_item_id, false ); // Get the new item
// Add custom meta data (afterwards)
$new_item->add_meta_data( '_wwp_wholesale_priced',$item->get_meta('_wwp_wholesale_priced'), true );
$new_item->add_meta_data( '_wwp_wholesale_role',$item->get_meta('_wwp_wholesale_role'), true );
$new_item->add_meta_data( '_amount_requested',$item->get_meta('_amount_requested'), true );
$new_item->add_meta_data( '_amount_colli',$item->get_meta('_amount_colli'), true );
$new_item->save(); // Save item
}
// Calculate totals and save data
$new_order->calculate_totals();
我应该工作。