Skip to content

Instantly share code, notes, and snippets.

@MogulChris
Created October 15, 2019 20:25
Show Gist options
  • Save MogulChris/8fa67eedf01ef759e92e33a8e784aaa0 to your computer and use it in GitHub Desktop.
Save MogulChris/8fa67eedf01ef759e92e33a8e784aaa0 to your computer and use it in GitHub Desktop.
WooCommerce programmatically create variations from all attributes
<?php
/*
WooCommerce has a handy feature in the admin UI to "Create variations from all attributes".
To do this programmatically (as of WooCommerce v3.7.0) use a modified version of link_all_variations() found in woocommerce/includes/class-wc-ajax.php
*/
function myplugin_create_variations($product_id){
wc_maybe_define_constant( 'WC_MAX_LINKED_VARIATIONS', 50 );
wc_set_time_limit( 0 );
if ( ! $product_id ) {
wp_die();
}
$product = wc_get_product( $product_id );
$data_store = $product->get_data_store();
if ( ! is_callable( array( $data_store, 'create_all_product_variations' ) ) ) {
wp_die();
}
echo esc_html( $data_store->create_all_product_variations( $product, WC_MAX_LINKED_VARIATIONS ) );
$data_store->sort_all_product_variations( $product->get_id() );
}//myplugin_create_variations()
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment