How do I update product attributes programatically on product save in Woocommerce

I am looking to update the attributes of the products in my store every time they are saved based on the content of several other fields.

However I am struggling to get my attributes to appear correctly.

Read More

Initially I tried to update the product based on the accepted answer to this question using the following function:

add_action( 'woocommerce_process_product_meta', 'update_dietary' );

function update_dietary( $object_id ) {
  wp_set_object_terms( $object_id, 'UK Manufactured', 'pa_dietary' , false);
}

This added "UK Manufactured" to the list of terms available for the "pa_dietary" taxonomy but it was not visible in the product attributes when I checked them.

Following this I tried a variation on the second answer supplied in the above question:

add_action( 'woocommerce_process_product_meta', 'update_dietary' );

function update_dietary( $object_id ) {
  $product_attributes = array();
  $product_attributes['pa_dietary'] = array(
      'name' => 'Dietary',
      'value' => 'UK Manufactured',
      'position' => 1,
      'is_visible' => 1,
      'is_variation' => 1,
      'is_taxonomy' => 0
  );

  update_post_meta( $object_id,'_product_attributes', $product_attributes);
}

This also failed to update the attributes for the products.

At this point I don’t know what to try next. Using the woocommerce_process_product_meta action seems to work, based on the fact that the term does get added to WordPress but I think there must be something I’m missing about how Woocommerce handles product attributes.

If anybody could point me in the right direction it would be very much appreciated.

Related posts

Leave a Reply

1 comment