提问人:ivanasetiawan 提问时间:11/17/2023 最后编辑:LoicTheAztecivanasetiawan 更新时间:11/17/2023 访问量:41
在 WooCommerce 上克隆订单时使用“add_product()”添加产品元数据
Add product metadata using `add_product()` when cloning an order on WooCommerce
问:
我正在为 WooCommerce Order 创建克隆功能。 我想要的是确保正确克隆产品项元数据。
/**
* 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
答:
1赞
LoicTheAztec
11/17/2023
#1
您的代码中存在一些错误和遗漏,请尝试以下操作:
/**
* 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 data
}
// Calculate totals and save order data
$new_order->calculate_totals();
我应该工作。
评论