wordpress 在WooCommerce上克隆订单时使用“add_product()”添加产品元数据

2ic8powd  于 2023-11-17  发布在  WordPress
关注(0)|答案(1)|浏览(179)

我正在为WooCommerce订单创建克隆功能。我想要的是确保正确克隆产品项目Meta数据。

/**
 * 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应该可以做到这一点,但我没有看到任何Meta被传递。我也尝试使用$item->add_meta_data$item->update_meta_data,但他们似乎不工作。我错过了什么?
目标:

当前:

ozxc1zmp

ozxc1zmp1#

你的代码中有一些错误和遗漏,请尝试以下方法:

/**
 * 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();

字符串
我应该工作。

相关问题