0
votes

How can I edit the shipping class of a product with code after updating it?

Here's what I have so far on functions.php. It worked with the product_cat term, but it is not working with product_shipping_class.

add_action('save_post_product', 'my_product_save', 10, 3);

function my_product_save( $post_id, $post, $update ) {

    $shipping_class_slug = 'international-standard-shipping';

    wp_set_object_terms( $post_id, $shipping_class_slug, 'product_shipping_class' ); 

}

Thanks!

1

1 Answers

0
votes

The save_post hook runs before the post_meta is updated. We need to use a hook which fires after the post_meta is updated or added. You should also be using the WooCommerce product class functions and not WordPress functions to set the shipping meta data.

add_action( 'added_post_meta', 'woo_on_product_save', 10, 4 );
add_action( 'updated_post_meta', 'woo_on_product_save', 10, 4 );

function woo_on_product_save( $meta_id, $post_id, $meta_key, $meta_value ) {
    if ( $meta_key == '_edit_lock' ) {
        if ( get_post_type( $post_id ) == 'product' ) { 
            $product = wc_get_product( $post_id );
            $int_shipping = get_term_by( 'slug', 'international-standard-shipping', 'product_shipping_class' );
            $product->set_shipping_class_id( $int_shipping->term_id );
            $product->save();
        }
    }
}