如何通过PHP将WooCommerce产品变体从一个产品复制到另一个?
WooCommerce 产品变体复制解决方案
你遇到的核心问题是:WooCommerce中没有set_available_variations()这个内置方法,因为产品变体是独立的WC_Product_Variation对象,不能直接批量赋值,需要逐个复制并关联到目标产品。下面是完整的实现代码,支持通过产品ID复制变体:
if (isset($_POST['submit'])) { // 获取源产品ID(根据表单选择) $source_product_id = 0; if ($_POST['product_type'] == 'panoramic') { $source_product_id = 54721; } elseif ($_POST['product_type'] == 'wide-panoramic') { $source_product_id = 54730; } if (!$source_product_id || !$_POST['product_id_to_fill']) { // 缺少必要ID,直接返回 return; } // 获取源产品和目标产品对象 $source_product = wc_get_product($source_product_id); $target_product = wc_get_product($_POST['product_id_to_fill']); // 验证产品类型:源产品必须是可变产品,目标产品转为可变产品(如果不是) if (!$source_product || $source_product->get_type() !== 'variable') { die('源产品不是有效的可变产品'); } if ($target_product->get_type() !== 'variable') { $target_product->set_type('variable'); $target_product->save(); // 重新获取对象确保类型更新 $target_product = wc_get_product($_POST['product_id_to_fill']); } // 步骤1:复制源产品的属性(变体依赖属性存在) $source_attributes = $source_product->get_attributes(); foreach ($source_attributes as $attribute) { // 设置属性为用于变体(variation) $attribute->set_variation(true); $attribute->set_visible(true); } $target_product->set_attributes($source_attributes); $target_product->save(); // 可选:清空目标产品原有变体(如果需要完全替换) foreach ($target_product->get_children() as $variation_id) { wp_delete_post($variation_id, true); } // 步骤2:逐个复制源产品的变体 foreach ($source_product->get_children() as $source_variation_id) { $source_variation = wc_get_product($source_variation_id); // 创建新的变体对象 $new_variation = new WC_Product_Variation(); $new_variation->set_parent_id($target_product->get_id()); // 复制核心字段 $new_variation->set_price($source_variation->get_price()); $new_variation->set_regular_price($source_variation->get_regular_price()); $new_variation->set_sale_price($source_variation->get_sale_price()); $new_variation->set_sku($source_variation->get_sku()); $new_variation->set_stock_quantity($source_variation->get_stock_quantity()); $new_variation->set_stock_status($source_variation->get_stock_status()); $new_variation->set_manage_stock($source_variation->get_manage_stock()); $new_variation->set_weight($source_variation->get_weight()); $new_variation->set_dimensions($source_variation->get_dimensions()); // 复制变体属性值 $variation_attributes = $source_variation->get_attributes(); $new_variation->set_attributes($variation_attributes); // 复制自定义元数据(如果有) $meta_data = $source_variation->get_meta_data(); foreach ($meta_data as $meta) { $new_variation->add_meta_data($meta->key, $meta->value, true); } // 保存新变体 $new_variation->save(); } // 最后同步目标产品的变体缓存 $target_product->save(); echo '变体复制完成!'; }
关键说明:
- 属性前置复制:变体依赖产品的属性(比如尺寸、颜色),必须先把源产品的属性复制到目标产品,否则新变体无法关联。
- 变体独立创建:每个变体都是独立的产品,需要重新创建
WC_Product_Variation对象,关联到目标产品ID后保存。 - 可选操作:代码中包含了清空目标产品原有变体的逻辑,如果需要保留原有变体,删除那部分即可。
- 元数据复制:如果你的变体有自定义字段(比如图片、自定义元值),代码中已经包含了元数据复制,确保所有信息迁移完整。
内容的提问来源于stack exchange,提问作者Enjabain
相关产品推荐
相关产品推荐

