在 WooCommerce 中以编程方式创建可变产品并添加新属性值
WooCommerce 提供了一个灵活的框架来管理产品,包括创建产品的能力具有独特属性值的产品变体。本指南将演示如何以编程方式创建 WooCommerce 变量产品并向其添加新属性值。
1.创建可变产品:
假设您有父级或可变产品 ID,您可以使用以下代码创建新的产品变体:
function create_product_variation($product_id, $variation_data) { // Get the parent variable product object $product = wc_get_product($product_id); $variation_post = array( 'post_title' => $product->get_name(), 'post_name' => 'product-' . $product_id . '-variation', 'post_status' => 'publish', 'post_parent' => $product_id, 'post_type' => 'product_variation', 'guid' => $product->get_permalink() ); // Insert the product variation $variation_id = wp_insert_post($variation_post); // Create an instance of the variation object $variation = new WC_Product_Variation($variation_id); ... }
2.添加新属性值:
对于要添加的每个属性和值,您需要检查该术语是否存在,如果不存在则创建它:
foreach ($variation_data['attributes'] as $attribute => $term_name) { $taxonomy = 'pa_' . $attribute; // The attribute taxonomy // Check if the term exists if (!term_exists($term_name, $taxonomy)) { wp_insert_term($term_name, $taxonomy); // Create the term } $term_slug = get_term_by('name', $term_name, $taxonomy)->slug; // Get the term slug // Set the attribute data in the product variation update_post_meta($variation_id, 'attribute_' . $taxonomy, $term_slug); }
3。设置附加变体数据:
通过调用变体对象上的适当方法来设置任何附加值,例如 SKU、价格和库存:
$variation->set_sku($variation_data['sku']); $variation->set_price($variation_data['regular_price']); $variation->set_manage_stock(true); $variation->set_stock_quantity($variation_data['stock_qty']); ...
4.保存变体:
最后,保存对变体所做的所有更改:
$variation->save();
示例用法:
创建具有两个属性和两个变体的可变产品:
$parent_id = 123; // Your parent variable product ID $variation_data_1 = array( 'attributes' => array( 'color' => 'Blue', 'size' => 'Small' ), 'sku' => 'VAR-1234-BLUE-SMALL', 'regular_price' => '29.99', 'stock_qty' => 20 ); $variation_data_2 = array( 'attributes' => array( 'color' => 'Green', 'size' => 'Medium' ), 'sku' => 'VAR-1234-GREEN-MEDIUM', 'regular_price' => '39.99', 'stock_qty' => 10 ); create_product_variation($parent_id, $variation_data_1); create_product_variation($parent_id, $variation_data_2);
以上是如何在 WooCommerce 中以编程方式创建可变产品并添加新属性值?的详细内容。更多信息请关注PHP中文网其他相关文章!