我正在为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应该可以做到这一点,但我没有看到传递任何meta.我也试过使用$item->add_meta_data$item->update_meta_data,但它们似乎不起作用.我遗漏了什么?

Goal: What I want

Current: Currently

推荐答案

您的代码中有一些错误和遗漏的内容,请try 以下操作:

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

我该工作了.

Php相关问答推荐

无法使用PHP DomDocument找到IMG元素

基于验证动态更改输入字段类(名称密码)&

如何发送woocommerce订单跟踪码与短信

根据用户组或登录状态显示或隐藏定价后添加的文本

无法在Laravel/Vue停靠容器中启动MySQL

Laravel;Composer安装突然返回选项快捷方式不能为空.

Mod_重写子目录中相应的php文件

通过访问单个产品页面更新WooCommerce产品元数据

不包括WooCommerce中单独销售的产品

PHP Laravel Web应用启动时间&>15秒

WooCommerce短代码,显示特定产品的购物车徽章中的当前数量

上传WordPress模板中的翻译文件(.mo和.po)

MongoDB Laravel Jenssegers 包:插入数据库时​​未定义的类常量PRIMARY

添加产品标签以通过 WooCommerce 邮箱通知订购商品

将图像作为 PHP post 响应发送到浏览器

当我激活插件时出现错误注意:未定义的偏移量:1

WooCommerce单个产品页面上启用额外选项卡的产品元框字段

Laravel Docker 几个数据库

我想更新表格中的结果并将它们发布到浏览器,但它不起作用

检测字符串是否包含Letter with Tilde或Letter + Combining Tilde