When saving a product, I want to check if the product has a specific attribute. In my case, pa_region
. If not, I want to add attribute sets and attribute terms to the product.
If the property pa_region
is already set, I don't want to update/change it.
I see there is a function (documentation) called wp_set_object_terms
. I tried a few ways but I think update_post_meta
is the right way.
From this answer I know how to check if a product has an attribute. I'll add that check later.
Currently I try to add the attribute first. Not working properly yet.
I found a similar question here and I tried to use that code to achieve my purpose. But this doesn't work. I guess the reason is that the feature requires properties that are already in the product? !
Edit: I checked. Even though the property pa_region
is set in the product, the code does not update its value.
This is my current code:
add_action('woocommerce_update_product', 'save_product_region'); function save_product_region( $post ) { if( in_array( $post->post_type, array( 'product' ) ) ){ $test = 'test'; $product_id = $post->ID; $product_attributes = get_post_meta( $product_id ,'_product_attributes', true); var_dump($product_attributes); // Loop through product attributes foreach( $product_attributes as $attribute => $attribute_data ) { // Target specif attribute by its name if( 'pa_region' === $attribute_data['name'] ) { // Set the new value in the array $product_attributes[$attribute]['value'] = $test; break; // stop the loop } } update_post_meta( $product_id ,'_product_attributes', $product_attributes ); } }
The first $post is not an object. will return the ID, which is good.