How to insert variable product with PHP?
-
When I try to use WC_Product_Variable() the variations are created but somehow not properly synced / assigned. Deleting and creating the variations from /wp-admin/ works but how can I properly add variations to a product with PHP code?
I currently have this:
public static function create_wc_variable_product($products_to_import, $common_items, $variant_name) { $unique_short_descs = array_unique(array_column($products_to_import, 'short_desc')); $product = new WC_Product_Variable(); $product->set_name($variant_name); $product->set_status('publish'); $product->set_description('Variable Product Description'); $product->set_short_description('Short Description'); $attribute = new WC_Product_Attribute(); $attribute->set_id(0); $attribute->set_name('Variation'); $attribute->set_options($unique_short_descs); $attribute->set_position(0); $attribute->set_visible(true); $attribute->set_variation(true); $product->set_attributes([$attribute]); $product->set_variation_attributes([$attribute]); $product->save(); $product_id = $product->get_id(); foreach ($products_to_import as $product_data) { $variation = new WC_Product_Variation(); $variation->set_parent_id($product_id); $variation->set_attributes(['Variation' => $product_data['short_desc']]); $variation->set_status('publish'); $variation->set_regular_price(isset($product_data['list_price']) ? $product_data['list_price'] : 0); $variation->set_sku(isset($product_data['article_nr']) ? $product_data['article_nr'] : null); $variation->save(); update_post_meta($variation->get_id(), 'hwp_var_gtin', isset($product_data['technical_details']['GTIN']) ? $product_data['technical_details']['GTIN'] : ''); } }
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- The topic ‘How to insert variable product with PHP?’ is closed to new replies.