在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中文網其他相關文章!