Skip to content

Instantly share code, notes, and snippets.

@lowhow
Last active November 1, 2015 16:37
Show Gist options
  • Save lowhow/4f7e974b4754843c2ec4 to your computer and use it in GitHub Desktop.
Save lowhow/4f7e974b4754843c2ec4 to your computer and use it in GitHub Desktop.
Advance Add attributes to WooCommerce product. Does not use global Attribute Taxonomy. Ensures attribute values are unique.
/**
* Add product attributes to Main/Parent product.
*
* Can add an array of attributes with an array of their respective values.
* Will check if product attribute exist. If so, will ensure attribute values are unique.
*
* @param int $post_id Parent Product ID.
* @param array $attr_names_values Array of product attributes with array of values.
*/
public function add_product_attributes( $post_id, $attr_names_values )
{
wp_set_object_terms ($post_id, 'variable', 'product_type');
/* Get existing _product_attributes. */
$current_attr = get_post_meta( $post_id, '_product_attributes' );
$attr_data = array();
/* Loop through each attribute */
foreach ( $attr_names_values as $attr_name => $attr_values )
{
/* Prepending 'pa_' to attribute key. Gonna skip the prefix for now. */
//$attr_sanitized_name = 'pa_' . sanitize_title( $attr_name );
$attr_sanitized_name = sanitize_title( $attr_name );
$new_attr_values = $attr_values;
$current_attr_values = $new_attr_values;
if ( isset( $current_attr[0] ) )
{
$current_attr_values = explode( '|', $current_attr[0][ $attr_sanitized_name ]['value'] );
/**
* Check is new attribute value already exist in current attribute values,
* if NOT exist, add in to the list.
* Skip if YES.
*/
if ( array_key_exists( $attr_sanitized_name, $current_attr[0] ) )
{
foreach ($new_attr_values as $new_attr_value) {
if ( ! in_array( $new_attr_value, $current_attr_values ) )
$current_attr_values[] = $new_attr_value;
}
}
}
/* Construct attribute data array and group them up. */
$attr_data += array(
$attr_sanitized_name => array(
'name' => $attr_name,
'value' => implode( '|', $current_attr_values ),
'is_visible' => 1,
'is_variation' => 1,
'is_taxonomy' => 0,
'position' => 0,
)
);
}
update_post_meta( $post_id, '_product_attributes', $attr_data, FALSE );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment