Overwriting Woocommerce product attribute on save

Viewed 46

I am trying to alter an attribute when the user saves a new product or updates an existing. If the product is a certain category the 'weight' should be N/A..

enter image description here

Here is my product as it should start which is fine. Now I want to add a weight field to it (Which already exists as an attribute) and assign the weight to N/A. Here's the end result I want to do programmatically.

enter image description here

Here is as far as I can get:

add_action( 'woocommerce_update_product', 'mp_sync_on_product_save', 10, 1 );
function mp_sync_on_product_save( $product_id ) {
     $product = wc_get_product( $product_id );
    if($product->category_ids[0] == 18) {
        //We are jewellery
        $post_id = $product->get_id();
        
        $product_attr = get_post_meta($post_id, '_product_attributes',true);//get the whole product attributes first
        $product_attr['pa_weight'] = array(
            'name'          => 'pa_weight',
            'value'         => 'N/A',
            'position'      => 1,
            'is_visible'    => 1,
            'is_variation'  => 1,
            'is_taxonomy'   => '1'
        );
        update_post_meta($post_id , '_product_attributes',$product_attr);
    }

}

Currently nothing seems to happen here. I hope I'm close so any help to get this over the line would be awesome. Thanks

0 Answers
Related