Skip to content

Instantly share code, notes, and snippets.

@sododesign
Forked from galalaly/import-variation.php
Created November 14, 2018 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sododesign/800a6dec746d7126100f6f7d02c16a7d to your computer and use it in GitHub Desktop.
Save sododesign/800a6dec746d7126100f6f7d02c16a7d 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 );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment