Skip to content

Instantly share code, notes, and snippets.

@lowhow
Last active November 1, 2015 16:36
Show Gist options
  • Save lowhow/56ab6e94c38409d8004e to your computer and use it in GitHub Desktop.
Save lowhow/56ab6e94c38409d8004e to your computer and use it in GitHub Desktop.
Add attributes to WooCommerce product
/**
* Create variable product.
*/
$post = array(
'post_title' => 'Product with attributes only PHP',
'post_content' => '',
'post_status' => 'publish',
'post_type' => "product"
);
$new_post_id = wp_insert_post( $post );
wp_set_object_terms ($new_post_id,'variable','product_type');
/**
* Add product attribute.
*/
$attr_names = array(
'Colour' => array( 'Red' ),
'Size' => array( 'Small', 'Large' )
);
$attr_data = array();
foreach ( $attr_names as $attr_name => $attr_values ) {
$attr_sanitized_name = 'pa_' . sanitize_title( $attr_name );
$attr_data += array(
$attr_sanitized_name => array(
'name' => $attr_name,
'value' => implode( '|', $attr_values ),
'is_visible' => 1,
'is_variation' => 1,
'is_taxonomy' => 0,
'position' => 0,
)
);
}
update_post_meta( $new_post_id, '_product_attributes', $attr_data, TRUE );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment