Prevent attributes from being overwritten during Product Set updates
If you are importing taxonomy-based attributes such as color or size or gender during your Product Set imports and do not want those values overwritten when your Product Set updates the products in its set, you'll need to add a little extra code.
This is useful if you edit product attribute information after a product has been imported by the Product Set.
What is a taxonomy-based attribute?
Taxonomy-based attributes are WooCommerce attributes that you have added here: WordPress Admin Area > Products > Attributes
Here's how to prevent your attributes from being overwritten during Product Set updates.
- 1
-
Create a custom plugin
If you haven't done so already, create a custom plugin.
- 2
-
Add custom code
Add the following custom code to your custom plugin:
/** * Prevent taxonomy-based (global) attributes from being overwritten when a Product Set * updates a product already in your store. * * @link http://stackoverflow.com/a/13454788/2489248 * @see wc_get_product_terms() * * @param array|string $value The current value of the $attribute for this $post. * @param string $attribute The slug of the attribute. Examples: pa_color or pa_shoe-size * @param array $post An array of post data including ID, post_title, post_status, etc... * @param array $product An array of product data returned from the Datafeedr API. * @param array $set A post array for this Product Set. * @param string $action The action the Product Set is performing. Either "insert" or "update". * * @return array|string The updated attribute's value. */ add_filter( 'dfrpswc_filter_attribute_value', function ( $value, $attribute, $post, $product, $set, $action ) { /** * You can also specify specific attributes like this: $attrs = [ 'color', 'size', ]; */ $attrs = array_column( wc_get_attribute_taxonomies(), 'attribute_name' ); if ( 'insert' === $action ) { return $value; } foreach ( $attrs as $attr ) { $name = dfrapi_string_starts_with( $attr, 'pa_' ) ? $attr : 'pa_' . $attr; if ( $name !== $attribute ) { continue; } $value = wc_get_product_terms( $post['ID'], $name, [ 'fields' => 'names' ] ); $value = implode( WC_DELIMITER, $value ); } return $value; }, 10, 6 );
- 3
-
Add your attribute slugs
In our example code above, we are preventing the attributes color and size from being overwritten. You can add to, remove from or modify this list of attributes. You can find your attribute slugs here: WordPress Admin Area > Products > Attributes
- 4
-
Save
Save your custom plugin file.
Now the next time your Product Set updates, those products which already have the color and size attributes will not have their attribute values changed.