


How to Create a WooCommerce Product Variation with New Attribute Values Programmatically?
How to Create a WooCommerce Product Variation with New Attribute Values Programmatically
Introduction
WooCommerce allows you to create variable products with different attributes and values. To add new variations programmatically, you need to consider the following:
- Ensure that the variable product (parent) has the desired attributes set.
- For each variation, either create the new attribute value or set it if it already exists.
Custom Function to Create Product Variation
The following custom function will create a product variation for a given variable product ID:
function create_product_variation( $product_id, $variation_data ){ // Get Variable product object (parent) $product = wc_get_product($product_id); // Create variation post data $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 variation post and create WC_Product_Variation object $variation_id = wp_insert_post( $variation_post ); $variation = new WC_Product_Variation( $variation_id ); // Iterate through variation attributes foreach ($variation_data['attributes'] as $attribute => $term_name ) { $taxonomy = 'pa_'.$attribute; // Attribute taxonomy // Create taxonomy if doesn't exist if( ! taxonomy_exists( $taxonomy ) ) register_taxonomy( $taxonomy, 'product_variation', array( 'hierarchical' => false, 'label' => ucfirst( $attribute ), 'query_var' => true, 'rewrite' => array( 'slug' => sanitize_title($attribute) ), ), ); // Check if term exists and create if not if( ! term_exists( $term_name, $taxonomy ) ) wp_insert_term( $term_name, $taxonomy ); // Create term $term_slug = get_term_by('name', $term_name, $taxonomy )->slug; // Get term slug // Check if post term exists and set if not $post_term_names = wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') ); if( ! in_array( $term_name, $post_term_names ) ) wp_set_post_terms( $product_id, $term_name, $taxonomy, true ); // Set attribute data in variation update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_slug ); } // Set other variation data if( ! empty( $variation_data['sku'] ) ) $variation->set_sku( $variation_data['sku'] ); if( empty( $variation_data['sale_price'] ) ){ $variation->set_price( $variation_data['regular_price'] ); } else { $variation->set_price( $variation_data['sale_price'] ); $variation->set_sale_price( $variation_data['sale_price'] ); } $variation->set_regular_price( $variation_data['regular_price'] ); if( ! empty($variation_data['stock_qty']) ){ $variation->set_stock_quantity( $variation_data['stock_qty'] ); $variation->set_manage_stock(true); $variation->set_stock_status(''); } else { $variation->set_manage_stock(false); } $variation->set_weight(''); // Reset weight $variation->save(); }
Example Usage
For a variable product with attributes "Size" and "Color", you can create a variation as follows:
$parent_id = 746; // Variable product ID $variation_data = array( 'attributes' => array( 'size' => 'M', 'color' => 'Green', ), 'sku' => '', 'regular_price' => '22.00', 'sale_price' => '', 'stock_qty' => 10, ); create_product_variation( $parent_id, $variation_data );
This will add a variation with the specified attributes and data to the variable product.
The above is the detailed content of How to Create a WooCommerce Product Variation with New Attribute Values Programmatically?. For more information, please follow other related articles on the PHP Chinese website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
