The following code should do the trick, auto adding To Product variations, the shipping class ID based on product attribute "Size" term value assigned to the variation.
It requires to have the same terms for Size product attribute and for shipping classes terms too ("Small", "Medium" and "Large" in your case)
The code:
add_action( 'woocommerce_save_product_variation', 'auto_add_shipping_method_based_on_size', 10, 2 );
function auto_add_shipping_method_based_on_size( $variation_id, $i ){
// Get the WC_Product_Variation Object
$variation = wc_get_product( $variation_id );
// If the variation hasn't any shipping class Id set for it
if( ! $variation->get_shipping_class_id() ) {
// loop through product attributes
foreach( $variation->get_attributes() as $taxonomy => $value ) {
if( 'Size' === wc_attribute_label($taxonomy) ) {
// Get the term name for Size set on this variation
$term_name = $variation->get_attribute($taxonomy);
// If the shipping class related term id exist
if( term_exists( $term_name, 'product_shipping_class' ) ) {
// Get the shipping class Id from attribute "Size" term name
$shipping_class_id = get_term_by( 'name', $term_name, 'product_shipping_class' )->term_id;
// Set the shipping class Id for this variation
$variation->set_shipping_class_id( $shipping_class_id );
$variation->save();
break; // Stop the loop
}
}
}
}
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.