Skip to content

Instantly share code, notes, and snippets.

@galalaly
Created January 13, 2015 23:00
Show Gist options
  • Save galalaly/2e629e5a1c84006a05f7 to your computer and use it in GitHub Desktop.
Save galalaly/2e629e5a1c84006a05f7 to your computer and use it in GitHub Desktop.
Create WooCommerce variations with PHP
<?php
// In a class constructor
$this->size_tax = wc_attribute_taxonomy_name( 'Size' );
$this->color_tax = wc_attribute_taxonomy_name( 'Color' );
// Insert the main product first
// It will be used as a parent for other variations (think of it as a container)
$product_id = wp_insert_post( array(
'post_type' => 'product',
'post_title' => $product_title,
'post_content' => $product_content,
'post_status' => 'publish' // can be anything else
) );
// Insert the attributes (I will be using size and color for variations)
$attributes = array(
$this->size_tax => array(
'name' => $this->size_tax,
'value' =>'',
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
),
$this->color_tax => array(
'name' => $this->color_tax,
'value' => '',
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
)
);
update_post_meta( $product_id, '_product_attributes', $attributes );
// Assign sizes and colors to the main product
wp_set_object_terms( $product_id, array( 'large', 'medium' ), $this->size_tax );
wp_set_object_terms( $product_id, array( 'red', 'blue' ) , $this->size_tax );
// Set product type as variable
wp_set_object_terms( $product_id, 'variable', 'product_type', false );
// Start creating variations
// The variation is simply a post
// with the main product set as its parent
// you might want to put that in a loop or something
// to create multiple variations with multiple values
$parent_id = $product_id;
$variation = array(
'post_title' => 'Product #' . $parent_id . ' Variation',
'post_content' => '',
'post_status' => 'publish',
'post_parent' => $parent_id,
'post_type' => 'product_variation'
);
// The variation id
$variation_id = wp_insert_post( $variation );
// Regular Price ( you can set other data like sku and sale price here )
update_post_meta( $variation_id, '_regular_price', 2 );
update_post_meta( $variation_id, '_price', 2 );
// Assign the size and color of this variation
update_post_meta( $variation_id, 'attribute_' . $this->size_tax, 'red' );
update_post_meta( $variation_id, 'attribute_' . $this->color_tax, 'large' );
// Update parent if variable so price sorting works and stays in sync with the cheapest child
WC_Product_Variable::sync( $parent_id );
?>
@sandeep2244
Copy link

this Code work very well in my script for variable product insertion with ( 'is_taxonomy' => '0' ) (Must)
But in front-end page of website attribute showing ('pa_size' and 'pa_color') But i want ('Size' and 'Color')
How to solve it??

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment